什么可能是一种更简单的代码编码方式?

时间:2017-10-08 14:12:35

标签: java loops if-statement do-while

我正在编写一个程序,允许学生计算每个班级的平均学生人数。目前,我的代码如下所示:

(双班是学生正在上课的班级数,每班的学生人数分配到class1,class2等)。

if (classes == 1) {
    System.out.printf("How many students are there in your 1 st class?%n");
    class1 = TextIO.getlnDouble();
    classes = classes + 1;
    System.out.printf("Do you have another class?");
    boolean response = TextIO.getlnBoolean();
  } else if (classes == 2);

等,所有9个可能的类别。 (我的学校只允许在一个学期内完成相当于6.5课程的学分,但其中一些可能由两学分或非学分课程组成。)

我可以用这个循环,但是如何将给定的数字分配给正确的双?即我怎样才能将class1替换为class2,class3等?

2 个答案:

答案 0 :(得分:4)

是的,循环可行。数组是存储多个相同类型变量的更好方法

你有没有半个学生?使用整数,而不是双打

int[] students = new int[classes];
for (int c = 0; c < classes; c++) {
    System.out.printf("How many students are there in class #%d?%n", c);
    students[c] = TextIO.getlnInt();
} 

答案 1 :(得分:1)

你可以这样做:

System.out.printf("How many classes are you taking?%n");
int classes = TextIO.getlnInt();
for(int class=1; class <= classes; class++) {
    System.out.printf("How many students are there in your %d class?%n", class);
    students += TextIO.getlnDouble();
}
double average = students / classes;
System.out.printf("There are on average %.2f students per class%n", average);

此代码应该按照您的要求执行!