为什么必须用值初始化某些变量(例如0,null)?

so8*_*857 4 java null

为什么有些字符串(例如topStudent1)必须设置为null,而其他字符串(例如name1)则不能,以避免编译错误?为什么有些双打(例如highScore)必须设置为0,而其他(例如score1)则不能,以避免编译错误?

public class Exercise05_09 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the number of students: ");
        int numOfStudents = input.nextInt();

        String name1;
        String name2;
        String topStudent1 = null;
        String topStudent2 = null;
        double score1;
        double score2;
        double highScore = 0;
        double nextHighScore = 0;
        int count = 2;

    while (count <= numOfStudents) {
        if (count == 2) {
        System.out.println("Enter a student name: ");
        name1 = input.next();
        System.out.println("Enter a student score: ");
        score1 = input.nextDouble();
        System.out.println("Enter a student name: ");
        name2 = input.next();
        System.out.println("Enter a student score: ");
        score2 = input.nextDouble();
                if (score1 > score2) {
                    highScore = score1;
                    topStudent1 = name1;
                    nextHighScore = score2;
                    topStudent2 = name2;
                }
                else {
                    highScore = score2;
                    topStudent1 = name2;
                    nextHighScore = score1;
                    topStudent2 = name1;
                }
        }
        else {
            System.out.println("Enter a student name: ");
            name1 = input.next();
            System.out.println("Enter a student score: ");
            score1 = input.nextDouble();
                if (score1 > highScore) {
                    nextHighScore = highScore;
                    highScore = score1;
                    topStudent2 = topStudent1;
                    topStudent1 = name1;
                }
                else if (score1 > nextHighScore) {
                    nextHighScore = score1;
                    topStudent2 = name1;
                }
        }
       count++;    
    }
    System.out.printf("Top two students:\n%s's score is %3.1f\n%s's score is %3.1f\n", topStudent1, highScore, topStudent2, nextHighScore);
     }
}
Run Code Online (Sandbox Code Playgroud)

谢谢!!

And*_*eas 6

在访问所有变量之前必须明确赋值(JLS§16),编译器会验证这一点:

当对其值进行任何访问时,每个局部变量(第14.4节)和每个空白final字段(第4.12.4节,第8.3.1.2节)必须具有明确赋值.

由于while循环可能根本不执行(例如用户输入1),因此topStudent1printf语句中使用4个变量(例如)需要在while循环之外初始化变量.

这种初始化不必在声明行上,但在那里做更简单.

相反,其他变量(例如name1)在while循环之后不会被使用,而是仅在循环内部使用,并且在它们被使用之前肯定被分配.