2017-10-20 63 views
-3

好的,所以我在課堂上給了這個項目,並且我能夠創造出大部分。唯一困擾的是n家庭的收入。它不斷爲每個家庭打印相同的結果。我不知道爲什麼這樣做..任何幫助將是偉大的。謝謝。爲所有家庭打印相同的值

public class Family { 

private double income; 
private int size; 

public Family()//set everything to 0 at first 
    { 
     income=0.0; 
     size=0; 
    } 

public Family(double newIncome, int newSize) 
    { 
     income=newIncome; 
     size=newSize; 
    } 

public void writeoutput() 
    { 
     int index = 0;//created variable for an array 

     System.out.println("how manny Families are there"); 
     Scanner input = new Scanner(System.in); 
     index=input.nextInt(); 
     int[]family=new int[index];//input how many families 

    } 
     for (int i=0;i<index;i++){ 

     System.out.println("Enter income in family["+i+"]"); 
     income=input.nextDouble(); 
     System.out.println("Enter size in family["+i+"]"); 
     family[i]=input.nextInt();//input amount of members 

    } 

    System.out.println("Values in array: "); 

    for (int i=0;i<index;i++) 
    { 
     System.out.println("Family["+i+"] has $"+this.income+" dollars for incom"); 
     } 

    for (int i=0;i<index;i++) 
    { 
     System.out.println("Family["+i+"] has "+family[i]+" members"); 
     } 
    } 

輸出

 how manny Families are there 
     3 
     Enter income in family[0] 
     43.2 
     Enter size in family[0] 
     5 
     Enter income in family[1] 
     653.5 
     Enter size in family[1] 
     8 
     Enter income in family[2] 
     234.5 
     Enter size in family[2] 
     6 
     Values in array: 
     Family[0] has $234.5 dollars for incom 
     Family[1] has $234.5 dollars for incom 
     Family[2] has $234.5 dollars for incom 
     Family[0] has 5 members 
     Family[1] has 8 members 
     Family[2] has 6 members 
+0

你確定進入家庭應該在那個'家庭'級?什麼是調用這個代碼?讓'writeOutput'只寫自己的輸出可能會更好,不要求輸入 – phflack

+1

這段代碼不能編譯。你在方法外有語句。請[編輯你的帖子](https://stackoverflow.com/posts/46854487/edit)。 –

+0

不用擔心我現在正在工作..謝謝 –

回答

0

既然你看起來是學習對象的數組,你Famili的[]應該是

Family[] family = new Family[index]; 

然後在循環

family[i] = new Family(); 
family[i].income = input.nextDouble(); 
family[i].size = input.nextInt(); 

而且在您打印輸出的最後部分ess變量槽系列[位置]。變量

1

我不會給你整個解決方案。但是你的代碼有很多缺陷。

你在哪裏使用成員變量sizeincome甚至構造函數。您沒有使用任何OOP功能。代碼在這裏是多餘的。

而不是使用int[]family=new int[index];使用Family families[] = new Family[index]並將數據存儲在成員變量incomesize