gpt4 book ai didi

java - 对象被视为未初始化的变量

转载 作者:行者123 更新时间:2023-12-01 13:46:33 25 4
gpt4 key购买 nike

我有一个 Student 类和我的主程序,我创建一个新的学生对象,如下所示:

学生 newStudent = new Student(newStudentName, newMarkOne, newMarkTwo, newMarkThree);

但是,当我稍后尝试访问学生类中的 printArrays 方法时,如下所示:

newStudent.printArrays();

我收到一条错误消息,newStudent 说:

java:变量 newStudent 可能尚未初始化

但是 Student.printArrays(); 工作正常。

此问题是否是由于直到运行时才创建对象造成的?我该如何修复这个错误?

编辑:

Student 的调用位置:

case 1:
System.out.println("Enter the student's name in this format - Surname,Forename: ");
newStudentName = input.next();
while (!newStudentName.matches("[A-Z][a-zA-Z]*,[A-Z][a-zA-Z]*")) {
System.out.println("Enter name in correct format - Surname,Forename (no whitespace and uppercase first letters)");
newStudentName = input.next();
}
System.out.println("Enter the first mark: ");
newMarkOne = input.nextInt();
System.out.println("Enter the second mark: ");
newMarkTwo = input.nextInt();
System.out.println("Enter the third mark: ");
newMarkThree = input.nextInt();
Student newStudent = new Student(newStudentName, newMarkOne, newMarkTwo, newMarkThree);
break;
case 2:
System.out.println("Which student would you like to delete?");
newStudent.printArrays();
break;

学生类(class):

public class Student {
private String studentName;
private int markOne, markTwo, markThree;
private double score;
private static String course = "French";
private static String[] studentNamesArray = new String[10];
private static int[][] studentMarksArray = new int[10][3];
private static int nameArrayCount, markArrayCount;

public Student(String newStudentName, int newMarkOne, int newMarkTwo, int newMarkThree) {
if (nameArrayCount < 10) {
this.studentName = newStudentName;
this.markOne = newMarkOne;
this.markTwo = newMarkTwo;
this.markThree = newMarkThree;
this.score = ((markOne + markTwo + markThree) / 3);
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
}
}

最佳答案

您的代码中可能有类似的内容:

Student newStudent;
if (condition) {
newStudent = new Student(newStudentName, newMarkOne, newMarkTwo, newMarkThree);
}

newStudent.printArrays(); // here you get the "might not have been initialized"

它不一定是 if block ,也可以是任何其他 block ,例如 try/catch。要修复此问题,请将 Student newStudent; 更改为 Student newStudent = null;

关于java - 对象被视为未初始化的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20329654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com