0

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

但是当我像这样放入.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

我想要的只是最后两个,因为它们是正确的。

4

1 回答 1

7

正如您在循环之前将 min 和 max 初始化为假值一样,您还应该将 minName 和 maxName 初始化为:

String minName = null;
String maxName = null;

否则,由于编译器无法保证循环至少执行一次,因此无法保证这些变量已被初始化为某个值(如错误消息所示)。

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

于 2013-05-05T09:10:45.320 回答