0

I can output the details from the student, but always when i do it displays

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

and the program crashes.

The array is null , I don't why and I don't know how to fix that. Please help me to understand, the problem should be around here..

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

    }

Anyways here comes my 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");
}

This is my client Class

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.");

    }

}

}

And here is my student class

 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;
        }

    }*/
   }
 }
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
Stiller77
  • 13
  • 1
  • 6
  • Please go through the [tour], the [help] and the [how to ask a good question](http://stackoverflow.com/help/how-to-ask) sections to see how this site works and to help you improve your current and future questions, which can help you get better answers. – Hovercraft Full Of Eels Apr 05 '16 at 15:33
  • 1
    The heuristic for NullPointerExceptions is almost always the same: You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. – Hovercraft Full Of Eels Apr 05 '16 at 15:35
  • The array is not null, but you call one index of the array where you never stored a `Student` object, so the object at this index is null . `list[a].DisplayOutput();` will crash when the object at index `a` is null, since you call a method on a `null` object . – Arnaud Apr 05 '16 at 15:36
  • You have an array with the length of 20 that potentially holds a ``student`` object in each of the 20 slots. But those slots are initally ``null`` and you call the ``DisplayOutput();`` on one of those slots that are still null. – f1sh Apr 05 '16 at 15:37
  • Yeah sorry, I am trying to read and understand the questions related to that since hours, but I don't get it. Im in the first semester for java and I'm not really good though. I thought I should just write the whole code. Because I'm not sure if the problem is only the display method or the array itself. – Stiller77 Apr 05 '16 at 15:37
  • `"I thought I should just write the whole code. Because I'm not sure if the problem is only the display method or the array itself."` -- which is why you should do necessary debugging **before** posting your question. If you had searched on how to debug NullPointerExceptions before posting, you'd find a road map on how to get started. Please keep this in mind for future questions. – Hovercraft Full Of Eels Apr 05 '16 at 15:40
  • Wow thank you very much for the many fast comments guys. @Berger can u tell me how I dont call the index of the array which is not stores. Should I start by a=1? – Stiller77 Apr 05 '16 at 15:41
  • @Stiller77 : the answer below shows you how to do it . – Arnaud Apr 05 '16 at 15:43

1 Answers1

6

The array isn't null.

The exception is thrown when you try to call a method on a null member of the array.

You iterate over the full array, but have not necessarily filled the entire array. Members that you have not assigned to reference an object are null.

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

One fix would be to stop iterating after you've hit the first 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();
    }
}

Another fix would be to remember in case 1 how many students were stored, and change the loop condition to reflect that.

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

By the way, in Java code it is almost universally accepted that:

  • Class names begin with an uppercase character.
  • Method names begin with a lowercase character.
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Wow thank you very much Andy, I tried to use the fix u mentioned, but I wrote student = list[a] ; instead of student student = list[a]; But the problem still occurs.. the second fix.. Do you mean with cntStudents, the Studentnumber I use as limit in the first for loop to get the Studentdetails? – Stiller77 Apr 05 '16 at 15:49
  • IT WORKED THANK YOU ANDY I APPRECIATE THAT, AND THANK YOU GUYS YOU ARE AWESOME!!!!!!!!!!!!!!!!! – Stiller77 Apr 05 '16 at 15:57
  • Damn Andy Im so happy I tried hours and hours to fix that.. I LOVE YOU MAN!!!!!! :D :D:D :D :D :D – Stiller77 Apr 05 '16 at 16:00