如何在for循环中接收对象的数据

时间:2019-05-25 14:07:18

标签: java

我正在尝试编写一个有两个对象的代码。我想使用相同的for循环为每个对象产生循环总和。我该怎么做呢?另外,我只有为c1创建的代码,有没有办法我也可以为c2编写代码而又没有冗余?

我只从遇到问题的文件中提供了一些代码。

Calorie.java


public void setCalorieSum(int calorieSum) {
    this.calorieSum = calorieSum;
}

public void setMealsAte(int mealsAte) {
    this.mealsAte = mealsAte;
}



CalorieTester.java

Calorie c1 = new Calorie();
Calorie c2 = new Calorie();
int num = 1;

System.out.println("Information for Day #" + num +": ");
c1.setMealsAte(number(console, "\t how many meals did you eat? "));

        for(int j = 1; j < c1.getMealsAte() + 1; j++) {
            c1.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
            int calorieSum += d1.setCalorieSum();
        }

System.out.println("-- Total caloric intake = \n"/* + c1.getCalorieSum + " --"*/);
num++;

1 个答案:

答案 0 :(得分:0)

您的想法看起来正确。无论如何,您需要在for循环之前对int卡路里和进行indel卡路里求和运算:

int calorieSum=0
for(int j = 1; j < c1.getMealsAte() + 1; j++) {
            c1.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
            calorieSum += d1.setCalorieSum();
        }

另外,如果我正确理解了代码的用途,其中c1和c2是需要用户填写的不同实体,则只需将创建的for循环设为:

int calorieSum1=0;
int calorieSum2=0;

for(int j = 1; j < c1.getMealsAte()+c2.getMealsAte() + 1; j++) {
            if (j<c1.getMealsAte()){
                  c1.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
                  calorieSum1 += d1.getCalorieSum();
             }
           else {
                 c2.setCalorieSum(number(console, "\t how many calories were consumed in meal " + j + "? "));
                 calorieSum2 += d2.getCalorieSum();
                }
        }

}
d1.setCalorieSum(calorieSum1);
d2.setCalorieSum(calorieSum2);

然后创建1个getter方法

public void getCaloriesSum(){
       return this.calorieSum;
}