4 回答

TA貢獻1776條經驗 獲得超12個贊
您沒有將用戶輸入存儲在for循環中的數組中。同樣在 while 循環中,您再次要求用戶輸入。所以刪除你的 for 循環。此外,無需存儲輸入即可找到最大值。只有一個變量就足夠了。這是用于查找最大值的未經測試的代碼。
import java.util.ArrayList;
import java.util.Scanner;
public class HighestGrade {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int greatest = -1;
int count = 0;
while (count<5) {
++count;
System.out.print("Enter a number: ");
int input = scan.nextInt();
if (input <= 100 && input >= 00) {
if(input >= greatest)
greatest = input;
}
else{
System.out.println("Error: Make sure the grade is between 0 and 100!\nEnter a new grade!");
}
}
System.out.println("\nHighest grade: "+greatest);
}
}

TA貢獻1786條經驗 獲得超11個贊
分數數組列表為空。您忘記在數組中插入值。
for (int i=0; i<5; i++) {
System.out.print("Enter a grade (between 0 and 100): ");
int temp = scan.nextInt();
if (input <= 100 && input >= 00) {
if( temp > greatest )
greatest = temp;
}
else{
System.out.println("Error: Make sure the grade is between 0 and
100!\nEnter a new grade!");
}
}

TA貢獻1906條經驗 獲得超3個贊
這不需要兩個循環。在 for 循環中,您只需讀取值。所以你可以簡單地刪除它。像這樣嘗試
import java.util.ArrayList;
import java.util.Scanner;
public class HighestGrade {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
ArrayList<Integer> scores = new ArrayList<Integer>();
int greatest = -1;
while (scores.size()<5) {
System.out.print("Enter a grade (between 0 and 100): ");
int input = scan.nextInt();
if (input <= 100 && input >= 00) {
scores.add(input);
if(input >= greatest)
greatest = input;
}
else{
System.out.println("Error: Make sure the grade is between 0 and 100!\nEnter a new grade!");
}
}
System.out.println("\nHighest grade: "+greatest);
}
}

TA貢獻1854條經驗 獲得超8個贊
問題似乎出在這里,您沒有在 for 循環中將輸入值添加到 ArrayList 分數中。這意味著第五個輸入僅添加到列表中并被考慮。所以對于這段代碼,沒有打印出最大值。只有最后一個值作為輸入。
for (int i=0; i<5; i++) {
System.out.print("Enter a grade (between 0 and 100): ");
scores.add(scan.nextInt());
}
添加回答
舉報