我有一个Student
课程和我的主程序,我创建了一个新的学生对象:
Student newStudent = new Student(newStudentName, newMarkOne, newMarkTwo, newMarkThree);
然而,当我稍后尝试访问学生类中的printArrays
方法时,如下所示:
newStudent.printArrays();
我的错误是newStudent
说:
java: variable newStudent might not have been initialized
但是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;
Student
上课:
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.*****");
}
}
}
答案 0 :(得分:1)
您的代码中可能有类似的内容:
Student newStudent;
if (condition) {
newStudent = new Student(newStudentName, newMarkOne, newMarkTwo, newMarkThree);
}
newStudent.printArrays(); // here you get the "might not have been initialized"
它不一定是if块,也可以是try / catch之类的任何其他块。要解决此问题,请将Student newStudent;
更改为Student newStudent = null;
。