我必须计算输入的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 the lowest 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 statements
时,就像这样:
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
我想要的只是最后两个因为那些是正确的。
答案 0 :(得分:7)
就像在循环之前将min和max初始化为假值一样,您还应该将minName和maxName初始化为:
String minName = null;
String maxName = null;
否则,由于编译器无法保证循环至少执行一次,因此无法保证这些变量已初始化为某个值(如错误消息所示)。
顺便说一句,你的代码应该以某种方式处理这种情况:如果inFile中有0个条目,你应该检测它(例如minName仍然是null),你可以写一条错误信息。