我只是一名初學者程序員,我被困在我的部分代碼中;有沒有辦法告訴編譯器,如果用戶輸入7,它將通過1 2 3 4 5 6和7而不是僅使用7?在Java中需要幫助(平均程序)
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循環,但是我會在哪裏插入循環?
(請記住,我只是個初學者。)
去閱讀有關[For循環(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for。 html) – OldProgrammer
請了解[Arrays](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)! –