我必须计算输入的 50 个等级中的最高和最低等级,并说出谁具有透视等级。这是问题代码:
max=-999;
min=1000;
while(inFile.hasNext())
{
name = inFile.next();
grade = inFile.nextInt();
inFile.nextInt();
if(grade > max)
{
max = grade;
maxName = name;
}
if(grade < min)
{
min = grade;
minName = name;
}
System.out.println(minName + " has the lowest grade of " + min);
System.out.println(maxName + " has the highest grade of " + max);
}
我尝试将 System.out.println(minName + "has theest Grade of "+ min);
放在我的 while
loop
之后但它给了我错误:
H:\Java\Lab6.java:202: error: variable maxName might not have been initialized
System.out.println(maxName + " has the highest grade of " + max);
^
但是当我将 .println
放入 if 语句
中时,如下所示:
if(grade > max)
{
max = grade;
maxName = name;
System.out.println(maxName + " has the highest grade of " + max);
}
if(grade < min)
{
min = grade;
minName = name;
System.out.println(minName + " has the lowest grade of " + min);
}
它给了我这个输出:
Robert has the highest grade of 70
Robert has the lowest grade of 70
Joel has the lowest grade of 64
Alice has the highest grade of 98
Larry has the lowest grade of 42
Christine has the lowest grade of 20
Alex has the lowest grade of 10
Mathew has the highest grade of 100
我想要的只是最后两个,因为它们是正确的。
最佳答案
就像在循环之前将 min 和 max 初始化为假值一样,您也应该将 minName 和 maxName 初始化为某个值:
String minName = null;
String maxName = null;
否则,由于编译器无法保证循环至少执行一次,因此无法保证这些变量已初始化为某个值(如错误消息所示)。
顺便说一句,您的代码应该以某种方式处理这种情况:如果 inFile 中有 0 个条目,您可能应该检测到它(例如,minName 仍然为空),并且您可以编写一条错误消息。
关于java - 希望它在循环后输出句子,但它不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16383012/