为所有系列打印相同的值

时间:2017-10-20 17:38:16

标签: java

好的,所以我在课堂上得到了这个项目,我能够创造出大部分内容。我唯一坚持的是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

2 个答案:

答案 0 :(得分:1)

我不会给你全部解决方案。但是你的代码有很多缺陷。

您在哪里使用成员变量sizeincome甚至构造函数。您没有使用任何OOP功能。代码在这里是多余的。

而不是使用int[]family=new int[index];使用Family families[] = new Family[index]并将数据存储在成员变量incomesize上。

答案 1 :(得分:0)

由于您希望学习对象数组,因此您的famili []应该是

Family[] family = new Family[index];

然后在你的循环中

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

在打印输出的最后一部分,您可以通过family [position] .variable

访问变量