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

标签 java compiler-errors initialization

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

相关文章:

java - 寻找for循环中的最大值

Java IntStream iterate vs generated 何时使用什么?

compiler-errors - opencl编译错误

java - 错误: constructor Miclass in class Miclass cannot be applied to given types;

javascript - jQuery,寻找一种更智能的初始化方式

c++ - 等号对大括号初始化有影响吗?例如。 'T a = {}' 与 'T a{}'

java - 线程局部初始化

java - 错误: incompatible types: possible lossy conversion from double to int

java - 列出所有可以在java中打开特定文件类型的已安装程序

javascript - 如何在 VScode 中设置 typescript ?