我正在尝试编写一个代码,其中一个类有两个对象。我想使用相同的 for 循环来为每个对象生成循环之和。我该怎么做呢?另外,我只有为 c1 创建的代码,有没有办法也可以为 c2 编写它,而不需要代码冗余?
我只提供了我遇到问题的文件中的一些代码。
卡路里.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++;
最佳答案
你的想法看起来是正确的。但是,您需要在 for 循环之前 intilize 并删除 int calorieSum,例如:
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;
}
关于java - 如何在 for 循环中接收对象的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305567/