我必須創建一個程序來計算每個學生的平均分數。我設法做到了這一點,但是我怎樣才能將分數限制在0到100之間?我已經搜索了其他問題和許多節目,以便在聲明期間放置。問題是我不知道該在哪裏添加。所以這裏是代碼:如何在for循環中設置限制?
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
int x; // Number of students
int y; // Number of tests per student
int Score = 0; //Score of each test for each student
double Average = 0; //Average score
double Total = 0; //Total score
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the number of students: ");
x = keyboard.nextInt();
System.out.println("Please enter the amount of test scores per student: ");
y = keyboard.nextInt();
for (int z = 0; z < x; z++)
{
System.out.println("Student " + (z + 1));
System.out.println("------------------------");
for (int g=0; g < y; g++)
{
System.out.print("Please enter score " + (g + 1) + ": ");
Total += new Scanner(System.in).nextInt();
Total += Score;
Average = (Total/y);
}
System.out.println("The average score for student " + (z + 1) + " is " + Average);
System.out.println(" ");
Total= 0;
}
keyboard.close();
}
}
如果還有其他方式請做狀態。提前致謝。
假設您需要驗證輸入的測試分數爲0-100。然後不需要時,只需將if else子句檢查輸入的分數是否在範圍內。 –
是的,這是問題,我不知道如何把其他 – Farhan
放在要求輸入分數之前。拋開煩惱,你爲什麼要分兩次?在第二個系統出來和g循環? – jace