Java NullPointerException pourquoi le tableau est-il null?


Je peux sortir les détails de l'étudiant, mais toujours quand je le fais, il affiche

Exception in thread "main" java.lang.NullPointerException
    at client.Client.main(Client.java:126)

Et le programme se bloque.

Le tableau est null, je ne sais pas pourquoi et je ne sais pas comment résoudre ce problème. Aidez-moi à comprendre, le problème devrait être ici..

   if (choice == 3) {
        for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
            //   list[i] = new student();
            list[a].DisplayOutput();

    }

, de toute façon voici mon code.

 package client;

 import java.util.Scanner;

 public class Client {
//my infos
public static void AuthorInformation() {

    System.out.print("__________________________________________\n"
            + "Student Name: xxxxxx xxxxxx\n"
            + "Student ID-Number: xxxxxx\n"
            + "Tutorial Timing: Wednesday 9:30 - 12:30 \n"
            + "Tutor Name: Mr xxxxxx\n\n"
            + "__________________________________________\n");
}

Ceci est ma classe client

public static void main(String[] args) {

    AuthorInformation(); //calls the method for my information

    student[] list = new student[20]; //my array
    student student = new student();

    int choice = 0; //variable for the choise of the menu

    Scanner keyboard = new Scanner(System.in); //Scanner class



    do {        //MY menu in the do-while, so that it runs at least once while user enters 7(quit)

        student.DisplayQuestions();

        choice = keyboard.nextInt();   //takes the entered value from the user

        if (choice == 1) {

            System.out.println("Enter the Number of Students you want to store: ");//Enter amount of students to be stored
             int studentNumber = keyboard.nextInt();

            // student.addStudent();
            for (int i = 0; i < studentNumber; i++) { //for loop is till the student number is achieved

                list[i] = new student();

                System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
                list[i].SetTitle(keyboard.next());

                System.out.println("First name (given name)");
                list[i].SetFirstName(keyboard.next());

                System.out.println("A last name (family name/surname)");
                list[i].SetFamilyName(keyboard.next());

                System.out.println("Student number (ID):");
                list[i].SetStudentID(keyboard.nextInt());

                System.out.println("Enter the Day of birth(1-31): ");
                list[i].SetDay(keyboard.nextInt());

                System.out.println("Enter the Month of birth (1-12): ");
                list[i].SetMonth(keyboard.nextInt());

                System.out.println("Enter The Year of birth: ");
                list[i].SetYear(keyboard.nextInt());

                System.out.println("Students First Assignment Mark (0 - 100): ");
                list[i].SetFirstMark(keyboard.nextInt());

                System.out.println("Students Second Assignment Mark (0 - 100): ");
                list[i].SetSecondMark(keyboard.nextInt());

                System.out.println("Enter the mark of Student weekly practical work (0-10) ");
                list[i].SetWeeklyMarks(keyboard.nextInt());

                System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
                list[i].SetFinalMark(keyboard.nextInt());
                /* System.out.println("- - - - - - - - - - - -  -");
                System.out.println("Do you want to add another Student? (Yes/No)");

                String a = keyboard.next();

                if (a.equalsIgnoreCase("yes")) {

                } else if (a.equalsIgnoreCase("no")) {
                    i = list.length + 1;
                }*/

            }

        }

        if (choice == 2) {

            int x = 2;
            double AverageNum = 0;
            for (int p = 0; p < x; p++) {   //This is to take the Average OverallMarks of all students

                AverageNum += list[p].OverallMarking();

            }
            System.out.println("Total Average Of Overall Marks is :" + AverageNum / 2);

        }

        if (choice == 3) {

            for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
                //   list[i] = new student();
                list[a].DisplayOutput();

        }
        }
        if (choice == 4) {    //To Display the distribution of grades awarded.

            System.out.println("\nGrade Distribution: \n" + student.GetCounterHD() + " HDs\n" + student.GetCounterD() + " Ds\n" + student.GetCounterC() + " Cs\n" + student.GetCounterP() + " Ps\n" + student.GetCounterN() + " Ns\n");

        }

        if (choice == 5) {

            System.out.println("Enter Student's ID Number to search for: "); // to take the id number from the user
            int FindID = keyboard.nextInt();

            boolean Found = false;
            // to find with the student ID Number details of the student.
            for (int i = 0; i < 10; i++) {
                if (FindID == list[i].GetStudentID()) {

                    list[i].DisplayOutput();
                    Found = true;
                    break;
                }
            }

        }

        if (choice == 6) {  //

            System.out.println("Enter Student's Name to search for: ");
            String SearchStudentName = keyboard.next(); //take the name of the student 
            boolean Found = false;
            //To find the name of the student it loops till it has it or the limit of studentnumbers are achieved.
            for (int i = 0; i < list.length; i++) {
                if (SearchStudentName.equalsIgnoreCase(list[i].GetFirstName())) {
                    list[i].DisplayOutput();
                    Found = true;
                    break;
                }
            }
        }

    } while (choice != 7);
    { //while statement quit the program

        System.out.println("\nYou Quit.");

    }

}

}

Et voici ma classe d'étudiant

 package client;

 import java.util.Scanner;


 public class student {
 //The instance vriables for students (Title, first name, family name,
 Student ID, date of birth in day month and year, first and second 
 assignment mark, mark of weekly practical work and final exam

private String Title;
private String FirstName;
private String FamilyName;
private long StudentID;
private int Day;
private int Month;
private int Year;
private float FirstMark;
private float SecondMark;
private float WeeklyMarks;
private float FinalMark;

 //those private instance variables are for the calculation of (first and
 second assignment mark, mark of weekly practical work and exam mark, final 
mark and overall mark)
private float FirstMarkPercentage;
private float SecondMarkPercentage;
private float WeeklyMarksPercentage;
private float ExamPercentage;
private String FinalGrade;
private float OverallMarks = 0;

//those private instance variables are to count the the marks(
private int CounterN = 0;
private int CounterP = 0;
private int CounterC = 0;
private int CounterD = 0;
private int CounterHD = 0;



public student(String Title, String FirstName, String FamilyName, long StudentID, int Day, int Month, int Year, float FirstMark, float SecondMark, float WeeklyMarks, float FinalMark) {

    this.Title = Title;
    this.FirstName = FirstName;
    this.FamilyName = FamilyName;
    this.StudentID = StudentID;
    this.Day = Day;
    this.Month = Month;
    this.Year = Year;
    this.FirstMark = FirstMark;
    this.SecondMark = SecondMark;
    this.WeeklyMarks = WeeklyMarks;
    this.FinalMark = FinalMark;
    this.FinalGrade = FinalGrade;
}

//This Method is to display  (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam)
public student() {

    Title = "";
    FirstName = "";
    FamilyName = "";
    StudentID = 0;
    Day = 0;
    Month = 0;
    Year = 0;
    FirstMark = 0;
    SecondMark = 0;
    WeeklyMarks = 0;
    FinalMark = 0;
}

//The methods starting with Get...(), are to return the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public String GetTitle() {
    return Title;
}

public String GetFirstName() {
    return FirstName;
}

public String GetFamilyName() {
    return FamilyName;
}

public long GetStudentID() {
    return StudentID;
}

public int GetDay() {
    return Day;
}

public int GetMonth() {
    return Month;
}

public int GetYear() {
    return Year;
}

public float GetFirstMark() {
    return FirstMark;
}

public float GetSecondMark() {
    return SecondMark;
}

public float GetWeeklyMarks() {
    return WeeklyMarks;
}

public float GetFinalMark() {
    return FinalMark;
}

public String GetFinalGrade() {
    return FinalGrade;
}

public int GetCounterHD() {
    return CounterHD;
}

public int GetCounterD() {
    return CounterD;
}

public int GetCounterC() {
    return CounterC;
}

public int GetCounterP() {
    return CounterP;
}

public int GetCounterN() {
    return CounterN;
}

public float GetOverallMarks() {
    return OverallMarks;
}

//The methods starting with Set...(), are to set the (Title, first name, family name, Student ID, date of birth in day month and year, first and second assignment mark, mark of weekly practical work and final exam and the marks N, P, C, D & HD)
public void SetTitle(String Title) {
    this.Title = Title;
}

public void SetFirstName(String FirstName) {
    this.FirstName = FirstName;
}

public void SetFamilyName(String FamilyName) {
    this.FamilyName = FamilyName;
}

public void SetStudentID(int StudentID) {
    this.StudentID = StudentID;
}

public void SetDay(int Day) {
    this.Day = Day;
}

public void SetMonth(int Month) {
    this.Month = Month;
}

public void SetYear(int Year) {
    this.Year = Year;
}

public void SetFirstMark(float FirstMark) {
    this.FirstMark = FirstMark;
}

public void SetSecondMark(float SecondMark) {
    this.SecondMark = SecondMark;
}

public void SetWeeklyMarks(float WeeklyMarks) {
    this.WeeklyMarks = WeeklyMarks;
}

public void SetFinalMark(float FinalMark) {
    this.FinalMark = FinalMark;
}

public void SetFinalGrade(String FinalGrade) {
    this.FinalGrade = FinalGrade;
}

public void SetOverallMarks(float OverallMarks) {
    this.OverallMarks = OverallMarks;
}

public boolean equals(student OtherStudent) {
    return (this.FirstName.equalsIgnoreCase(OtherStudent.FirstName)) && (this.FamilyName.equalsIgnoreCase(OtherStudent.FamilyName));
}

//this method is for the calculation of (first and second assignment mark, mark of weekly practical work and exam mark, final mark and overall mark)
public float OverallMarking() {
    FirstMarkPercentage = ((FirstMark / 100) * 20);

    SecondMarkPercentage = ((SecondMark / 100) * 20);

    WeeklyMarksPercentage = ((WeeklyMarks / 10) * 10);

    ExamPercentage = ((FinalMark / 100) * 50);

    OverallMarks = FirstMarkPercentage + SecondMarkPercentage + WeeklyMarksPercentage + ExamPercentage; //for the overall mark returns 
    return OverallMarks;
}

//this function arranges the grade calculations and returns the final grade
public String GradeCalculations() {

    if (OverallMarks >= 80 && OverallMarks <= 100) { // if grade lies within this range print HD
        FinalGrade = "HD";
        CounterHD++;
    } else if (OverallMarks >= 70 && OverallMarks < 80) { // if grade lies within this range print D
        FinalGrade = "D";
        CounterD++;
    } else if (OverallMarks >= 60 && OverallMarks < 70) { // if grade lies within this range print C
        FinalGrade = "C";
        CounterC++;
    } else if (OverallMarks >= 50 && OverallMarks < 60) { // if grade lies within this range print P
        FinalGrade = "P";
        CounterP++;
    } else if (OverallMarks < 50 && OverallMarks >= 0) { // if grade lies within this range print N
        FinalGrade = "N";
        CounterN++;
    }
    return FinalGrade;
}

public void DisplayQuestions() {

    System.out.println("\n Welcome to the Menu to perform one of the following operations (You must enter a number between 1-7):");
    System.out.println("(1) To add the Student Information.");
    System.out.println("(2) To Display the Output from the Average Overall Mark for students.");
    System.out.println("(3) To Display all current Student Information.");
    System.out.println("(4) To Display the distribution of grades awarded.");
    System.out.println("(5) for entering a student ID Number To view all details of the student.");
    System.out.println("(6) for entering a student name To view all details of the student.");
    System.out.println("(7) Quit");
    System.out.println("\n__________________________________________");
}

//This function displays the details of the student with before calculated marks.
public void DisplayOutput() {

    System.out.println("\nName: " + GetTitle() + " " + GetFirstName() + " " + GetFamilyName());
    System.out.println("Student ID: " + GetStudentID());
    System.out.println("Date of Birth: " + GetDay() + "/" + GetMonth() + "/" + GetYear());
    System.out.println("Assignment 1 Marks: " + GetFirstMark());
    System.out.println("Assignment 2 Marks: " + GetSecondMark());
    System.out.println("Weekly Practical Marks: " + GetWeeklyMarks());
    System.out.println("Final Exam Marks: " + GetFinalMark());
    System.out.println("Final Marks & Grade: " + OverallMarking() + "/" + GradeCalculations());

}

public void addStudent() {
   /*Scanner keyboard = new Scanner(System.in);
    for (int i = 0; i < list.length; i++) { //for loop is till the student number is achieved

        list[i] = new student();

        System.out.println("\nTitle of the student (eg, Mr, Miss, Ms, Mrs etc): ");
        list[i].SetTitle(keyboard.next());

        System.out.println("First name (given name)");
        list[i].SetFirstName(keyboard.next());

        System.out.println("A last name (family name/surname)");
        list[i].SetFamilyName(keyboard.next());

        System.out.println("Student number (ID):");
        list[i].SetStudentID(keyboard.nextInt());

        System.out.println("Enter the Day of birth(1-31): ");
        list[i].SetDay(keyboard.nextInt());

        System.out.println("Enter the Month of birth (1-12): ");
        list[i].SetMonth(keyboard.nextInt());

        System.out.println("Enter The Year of birth: ");
        list[i].SetYear(keyboard.nextInt());

        System.out.println("Students First Assignment Mark (0 - 100): ");
        list[i].SetFirstMark(keyboard.nextInt());

        System.out.println("Students Second Assignment Mark (0 - 100): ");
        list[i].SetSecondMark(keyboard.nextInt());

        System.out.println("Enter the mark of Student weekly practical work (0-10) ");
        list[i].SetWeeklyMarks(keyboard.nextInt());

        System.out.println("Please Enter the Marks for the final Exam(0 - 100): ");
        list[i].SetFinalMark(keyboard.nextInt());
        System.out.println("- - - - - - - - - - - -  -");
        System.out.println("Do you want to add another Student? (Yes/No)");

        String a = keyboard.next();

        if (a.equalsIgnoreCase("yes")) {
            addStudent();
        } else if (a.equalsIgnoreCase("no")) {
           i=list.length+1;
        }

    }*/
   }
 }
Author: Vikrant Kashyap, 2016-04-05

1 answers

Le tableau n'est pas null.

L'exception est levée lorsque vous essayez d'appeler une méthode sur un null membre de la matrice.

Vous parcourez le tableau complet, mais n'avez pas nécessairement rempli le tableau entier. Les membres que vous n'avez pas affectés à la référence d'un objet sont nuls.

for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
    //   list[i] = new student();
    list[a].DisplayOutput();
}

Un correctif serait d'arrêter l'itération après avoir atteint le premier null.

for (int a = 0; a < list.length; a++) { //To Display all current Student Information.
    //   list[i] = new student();
    student student = list[a];
    if ( null == student ) {
       break;
    }
    else {
       list[a].DisplayOutput();
    }
}

Une autre solution serait de se rappeler dans le cas 1 combien d'étudiants ont été stockés, et de changer la boucle condition pour refléter cela.

for (int a = 0; a < cntStudents; a++) { //To Display all current Student Information.

, dans le code Java, il est presque universellement admis que:

  • Les noms de classe commencent par un caractère majuscule.
  • Les noms de méthodes commencent par un caractère minuscule.
 4
Author: Andy Thomas, 2016-04-05 15:41:57