希望它在循环后输出句子,但它不会编译

希望它在循环后输出句子,但它不会编译

问题描述:

我必须计算输入的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); 

} 

我试过后,我的whileloopSystem.out.println(minName + " has the lowest grade of " + min);但它给我的错误:

H:\Java\Lab6.java:202: error: variable maxName might not have been initialized 
    System.out.println(maxName + " has the highest grade of " + max); 
        ^

但是,当我把.printlnif 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

它可能是你声明“minName”和“maxName”但尚未初始化它。如果是这样,可能有可能你不会进入任何if子句,并且你以后不会初始化它。 – 2013-05-05 09:10:25

正如你在循环之前初始化的最小值和最大值,以假值,你也应该初始化minName和maxName的东西:

String minName = null; 
String maxName = null; 

否则,因为编译器不能保证循环至少执行一次,它不能保证这些变量已被初始化为某个值(如错误信息所示)。

顺便说一句,你的代码应该以某种方式处理这种情况:如果inFile中有0条记录,你应该可以检测到它(例如,minName仍然为空),并且你可以写出一条错误消息。

+0

非常感谢:D – XanderXIV 2013-05-05 09:28:46