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());
}
添加回答
举报