2013-05-22 3 views
0

Я пытаюсь написать содержимое переменной из другого класса.не может печатать переменную из другого класса?

кода, где устанавливаются переменным, обратите внимание, что операторы печати, что позволяет мне знать, сколько калорий переменный содержат в данный момент, это работает именно так, как это должно это не 0, по крайней мере

 edit 


import java.util.*; //importing utilities use the Scanner 

public class food extends products{ 
    //variable declaration 
private String[] foodName; 
private String[] drinkName; 
private String[] NoNo; 

public int calories; 
public int protz; 
public int carbz; 
public int fatz; 

Scanner input = new Scanner(System.in);//importing scanner and creating an object for it 
Interface inte = new Interface(); //creating an object interface 
caloriesmain m = new caloriesmain(); // creating a main class object to enable the exit to main menu 



    public void setFood(){ 
     this.name = "Food"; //overriding name variable inherited from class products to "Food" 
     this.description = "NB!The amount of nutrition is based on the raw weight of product with skin where applicable";//overriding description variable inherited from class products to a descriptive message 
     System.out.println(name); // printing the header of the Menu 

      //Storing items in to the array  
     String[] foodNA = {"1. Chicken", "2.Eggs", "3. Turkey", "4. Pork", "5. Beef", "6. Fish", "7, Rice"}; //storing food names 
     Integer[] nutriCalories = {230, 84, 194, 149, 150, 82, 111};//storing calories for each food name 
     Integer[] nutriProtein = {43, 6, 29, 28, 25, 18, 3};//Storing protein amount 
     Integer[] nutriCarb = {0, 1, 0, 0, 0, 0, 23};//storing carbohydrate amount 
     Integer[] nutriFat = {5, 6, 8, 3, 4, 1, 1};//storing fat amount 
     this.foodName = foodNA; 
     //converting arrays to arraylists(reason for conversion: could not find a way to index a regular array) 
     List<Integer> intList = Arrays.asList(nutriCalories); 
     List<Integer> intList2 = Arrays.asList(nutriProtein); 
     List<Integer> intList3 = Arrays.asList(nutriCarb); 
     List<Integer> intList4 = Arrays.asList(nutriFat); 


     System.out.println(description); //displaying an informative message  
     System.out.println(Arrays.toString(getFood()));//displaying all of the stored food names 
     System.out.println("8. Display Current intake"); 
     System.out.println("9. Next"); 

     int option = input.nextInt();//calling scanner to store an integer entered by the user in option variable 


     if (option == 1){     //if user chooses option number 1 
      int cals = intList.get(0);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(0);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(0);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(0);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 

     else if (option == 2){     //if user chooses option number 1 
      int cals = intList.get(1);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(1);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(1);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(1);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 
     else if (option == 3){     //if user chooses option number 1 
      int cals = intList.get(2);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(2);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(2);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(2);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 
     else if (option == 4){     //if user chooses option number 1 
      int cals = intList.get(3);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(3);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(3);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(3);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 
     else if (option == 5){     //if user chooses option number 1 
      int cals = intList.get(4);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(4);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(4);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(4);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 

     else if (option == 6){     //if user chooses option number 1 
      int cals = intList.get(5);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(5);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(5);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(5);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 

      else if (option == 7){     //if user chooses option number 1 
      int cals = intList.get(6);    //stores the amount of calories that is on index 0 in the arraylist 
      int prots = intList2.get(6);    //stores the amount of protein that is on index 0 in the arraylist 
      int carbs = intList3.get(6);   //stores the amount of carbohydrates that is on index 0 in the arraylist 
      int fats = intList4.get(6);    //stores the amount of fat that is on index 0 in the arraylist 

      System.out.println("+" + cals);//print out how many calories did this product add to the total amount 
      calories +=cals;//adds calories to the current amount 
      protz +=prots;//adds protein to the current amount 
      carbz +=carbs;//adds carbohydrates to the current amount 
      fatz +=fats; //adds fat to the current amount 
      System.out.println("total: " + calories);//displays the running total of the calories after each choice 
      setFood(); //displays the list again if user needs to add more than one product   
      } 

     else if(option == 8){ 
      System.out.println("Current intake \n Calories:" + calories + "\nProtein: " + protz + "\nCarbohydrates: " + carbz + "\nFats :" +fatz); 
      setFood(); 
     } 
     else if(option==9){// if user chooses 9 then the next method is called 

       setDrink(); 
     } 
    } 

    public String[] getFood(){ 

     return foodName; 

    } 


    public void setDrink(){ 
     this.name = "Drinks"; 
     System.out.println(name); 


     String[] drinkNA = {"1. Coffee", "2.Tea", "3. Ionised Drinks", "4. Soda", "5. Cola", "6. Diet Coke", "7. Milk"}; 
     Integer[] nutriCalories = {3, 3, 80, 11, 12, 0, 42}; 
     Integer[] nutriProtein = {0, 0, 0, 0, 0, 0, 4}; 
     Integer[] nutriCarb = {0, 1, 1, 3, 3, 0, 5}; 
     Integer[] nutriFat = {0, 0, 0, 0, 0, 0, 1}; 
     this.drinkName = drinkNA; 
     List<Integer> intList = Arrays.asList(nutriCalories); 
     List<Integer> intList2 = Arrays.asList(nutriProtein); 
     List<Integer> intList3 = Arrays.asList(nutriCarb); 
     List<Integer> intList4 = Arrays.asList(nutriFat); 


     System.out.println(Arrays.toString(getDrink())); 
     System.out.println("8. Display current Intake"); 
     System.out.println("9. Next"); 


      int option = input.nextInt(); 


     if (option == 1){ 
      int cals = intList.get(0); 
      int prots = intList2.get(0);    
      int carbs = intList3.get(0);   
      int fats = intList4.get(0);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink(); 

      } 

     else if (option == 2){ 
      int cals = intList.get(1); 
      int prots = intList2.get(1);    
      int carbs = intList3.get(1);   
      int fats = intList4.get(1);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink();   
      } 


     else if (option == 3){ 
      int cals = intList.get(2); 
      int prots = intList2.get(2);    
      int carbs = intList3.get(2);   
      int fats = intList4.get(2);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink();   
      } 
     else if (option == 4){ 
      int cals = intList.get(3); 
      int prots = intList2.get(3);    
      int carbs = intList3.get(3);   
      int fats = intList4.get(3);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink();   
      } 

      else if (option == 5){ 
      int cals = intList.get(4); 
      int prots = intList2.get(4);    
      int carbs = intList3.get(4);   
      int fats = intList4.get(4);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink();   
      } 
       else if (option == 6){ 
      int cals = intList.get(5); 
      int prots = intList2.get(5);    
      int carbs = intList3.get(5);   
      int fats = intList4.get(5);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink();   
      } 
        else if (option == 7){ 
      int cals = intList.get(6); 
      int prots = intList2.get(6);    
      int carbs = intList3.get(6);   
      int fats = intList4.get(6);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink();   
      } 





      else if(option == 8){ 
      System.out.println("Current intake \n Calories:" + calories);   
      setDrink(); 
     } 

     else if(option==9){ 

       setNono(); 
     } 


    } 

public String[] getDrink(){ 

     return drinkName; 

    } 





public void setNono(){ 
     this.name = "Restricted products"; 
     this.description = "Alcoholic drinks are measured 'per shot'(30ml),. rest of the food is measured in average serving sizes"; 

     System.out.println(name); 


     String[] Nono = {"1. Drugs", "2.Whiskey", "3. Vodka", "4. Fries", "5. Hamburger", "6. Pizza"}; 
     Integer[] nutriCalories = {0, 70, 85, 192, 300, 530}; 
     Integer[] nutriProtein = {0, 0, 0, 3, 15, 21}; 
     Integer[] nutriCarb = {0, 0, 0, 25, 35, 55}; 
     Integer[] nutriFat = {0, 0, 0, 10, 11, 25}; 
     this.NoNo = Nono; 
     List<Integer> intList = Arrays.asList(nutriCalories); 
     List<Integer> intList2 = Arrays.asList(nutriProtein); 
     List<Integer> intList3 = Arrays.asList(nutriCarb); 
     List<Integer> intList4 = Arrays.asList(nutriFat); 

     System.out.println(description);  
     System.out.println(Arrays.toString(getNono())); 
     System.out.println("7. Display current Intake"); 
     System.out.println("8. Exit"); 


      int option = input.nextInt(); 


     if (option == 1){ 
      int cals = intList.get(0); 
      int prots = intList2.get(0);    
      int carbs = intList3.get(0);   
      int fats = intList4.get(0);    

      System.out.println("Consuming Drugs can harm you and others around you); 
      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setDrink(); 

      } 

     else if (option == 2){ 
      int cals = intList.get(1); 
      int prots = intList2.get(1);    
      int carbs = intList3.get(1);   
      int fats = intList4.get(1);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setNono();   
      } 


     else if (option == 3){ 
      int cals = intList.get(2); 
      int prots = intList2.get(2);    
      int carbs = intList3.get(2);   
      int fats = intList4.get(2);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setNono();   
      } 
     else if (option == 4){ 
      int cals = intList.get(3); 
      int prots = intList2.get(3);    
      int carbs = intList3.get(3);   
      int fats = intList4.get(3);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setNono();   
      } 

      else if (option == 5){ 
      int cals = intList.get(4); 
      int prots = intList2.get(4);    
      int carbs = intList3.get(4);   
      int fats = intList4.get(4);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setNono();   
      } 
       else if (option == 6){ 
      int cals = intList.get(5); 
      int prots = intList2.get(5);    
      int carbs = intList3.get(5);   
      int fats = intList4.get(5);    


      System.out.println("+" + cals); 
      calories +=cals; 
      protz +=prots; 
      carbz +=carbs; 
      fatz +=fats; 
      System.out.println("total: " + calories); 
      setNono();   
      } 






     else if(option == 7){ 

      ; 

      printIntake(); 
       setNono(); 

     } 




     else if(option==8){ 



       m.main(Nono); //exit to main menu 
     } 


    } 

public void printIntake(){ 
    System.out.println(calories);  

} 



public String[] getNono(){ 
    return NoNo; 

} 




} 

переменная, которую я пытаюсь написать это «калории» она устанавливается из массива, а вот класс, где я пытаюсь записать переменную в текстовый файл:

import java.io.*; 
import java.util.*; 

public class saveLoad extends caloriesmain{ 

public food FO = new food(); 


    private Scanner x; 

public void save(){ 
System.out.println(); 

      try { 

     File file = new File("example.txt"); 
     BufferedWriter output = new BufferedWriter(new FileWriter(file)); 
     output.write("calories" + FO.calories); 
     output.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

Это может быть очень неправильный способ сделать это, я очень новичок в java, но в моей голове он должен j ust напечатайте его, но он печатает 0.

+0

имя первого класса - «еда» от – user2209644

+0

. Вам нужно указать код для всего класса «еда» (его следует называть «Продовольствием»). Вероятно, это проблема с переменной областью, и от показанного кода невозможно отлаживать. –

+1

Кроме того, я бы, вероятно, сбросил все вещи 'prots' и' protz', он исключительно устойчив к простому чтению кода. –

ответ

0

Как класс saveLoad знает, что такое пища?

Что вы пытаетесь сделать, потребуется constructor

Примером этого является:

import java.io.*; 
import java.util.*; 

public class SaveLoad extends caloriesmain{ 

public food FO; 
private Scanner x; 

public SaveLoad(int calories){ 
    FO= new food(calories); 
} 

public void save(){ 
System.out.println(); 

      try { 

     File file = new File("example.txt"); 
     BufferedWriter output = new BufferedWriter(new FileWriter(file)); 
     output.write("calories" + FO.calories); 
     output.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

В конструкторе я только предполагаю, параметры класса пищи.

Чтобы получить доступ к этому классу все, что вам нужно сделать в основной код создает новый экземпляр этого:

SaveLoad save= new SaveLoad(calories); 

Затем вы можете вызывать функцию сохранения, просто вызывая это в основной программе:

save.save(); 

в качестве альтернативы, пропустить создание экземпляра переменной FO:

import java.io.*; 
import java.util.*; 

public class SaveLoad extends caloriesmain{ 

private int calories; 
private Scanner x; 

public SaveLoad(int calories){ 
    this.calories=calories; 
} 


//because we've called the calories integer a private variable we need a set method 
//it can only be seen from within this class 
public void setCalories(int calories){ 
    this.calories=calories 
} 

public void save(){ 
System.out.println(); 

      try { 

     File file = new File("example.txt"); 
     BufferedWriter output = new BufferedWriter(new FileWriter(file)); 
     output.write("calories" + FO.calories); 
     output.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 

к установить различные калории экземпляра класса saveLoad и установить калории:

SaveLoad save= new SaveLoad(calories); 
save.setCalories(10); 
save.save(); 

Однако, в то время как это решит вашу проблему, вы должны думать об иерархии своего класса.

+0

Большое спасибо, я понимаю, что я, вероятно, все испортил, однако мой основной метод говорит, что static saveLoad loadFile = new saveLoad (калории); не может найти символ калорий? – user2209644

+0

Прежде всего попробуйте его с номером, я просто поместил 'calories' в качестве переменной, чтобы попробовать и работать с ним с вашим кодом;) Устремился вверх, хотя, когда вы создаете класс, подумайте о том, что нужно делать в нем , например еда не включает в себя напиток. Но еда будет включать как напиток, так и некоторую пищу. – James

+0

Отличное введение в классы [Java Classes] (http://docs.oracle.com/javase/tutorial/java/javaOO/classes.html) – James

Смежные вопросы