我只是一个初级程序员,我被困在我的一部分代码上;有没有办法告诉编译器,如果用户输入 7,它将通过 1 2 3 4 5 6 和 7 而不是只使用 7?
import java.util.Scanner;
public class Average {
int tests;
int grade1, grade2, grade3, grade4, grade5, grade6, grade7, grade8, grade9, grade10;
int total;
double average;
public void Average1() {
Scanner input = new Scanner(System.in);
System.out.println("Enter how many tests you will use. (Minimum 3, Maximum 10.) ");
tests = input.nextInt();
System.out.println("Enter the grade of your first test. (Do not include %)");
grade1 = input.nextInt();
System.out.println("Enter the grade of your second test. (Do not include %)");
grade2 = input.nextInt();
System.out.println("Enter the grade of your third test. (Do not include %)");
grade3 = input.nextInt();
switch (tests) {
case 4 : System.out.println("Enter the grade of your fourth test. (Do not include %)");
grade4 = input.nextInt();
break;
case 5 : System.out.println("Enter the grade of your fifth test. (Do not include %)");
grade5 = input.nextInt();
break;
case 6 : System.out.println("Enter the grade of your sixth test. (Do not include %)");
grade6 = input.nextInt();
break;
case 7 : System.out.println("Enter the grade of your seventh test. (Do not include %)");
grade7 = input.nextInt();
break;
case 8 : System.out.println("Enter the grade of your eighth test. (Do not include %)");
grade8 = input.nextInt();
break;
case 9 :System.out.println("Enter the grade of your ninth test. (Do not include %)");
grade9 = input.nextInt();
break;
case 10 : System.out.println("Enter the grade of your tenth test. (Do not include %)");
grade10 = input.nextInt();
break;
}
total = grade1 + grade2 + grade3;
average = total/tests;
}
在这个例子中,我试图制作一个基本的平均值计算器。 (这只是一个类,其他代码在单独的类中。)我需要询问用户他将输入多少个测试。 (它会自动通过 1 - 3)所以如果用户输入 6 个测试,我如何告诉编译器不要直接进入 6。我希望它通过 1-6。人们说我需要使用 for 循环,但我应该在哪里插入循环?
(请记住我只是一个初学者。)
最佳答案
您只需要使用循环来保持总计,并使用循环来收集他们为第一个问题指定的条目数。您可能希望向以下内容添加一些错误检查以处理错误的输入(比如为测试次数输入零)。
import java.util.Scanner;
public class Average {
int tests;
int total = 0;
double average;
public void Average1() {
Scanner input = new Scanner(System.in);
System.out.println("Enter how many tests you will use. (Minimum 3, Maximum 10.) ");
tests = input.nextInt();
for (int i = 1; i <= tests; ++i) {
System.out.println("Enter the grade of for test " + i + ". (Do not include %)");
total += input.nextInt();
}
average = total/tests;
}
}
关于java - 需要 Java 方面的帮助(普通程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21970662/