-2

First Class which is the main class

public class JavaMethod {
    public static void main (String[] args){

        JavaMethod javaMethod = new JavaMethod();
        javaMethod.makeChoice();

    }

    public void makeChoice(){
        Scanner console = new Scanner(System.in);

        System.out.println("Enter S, T or C");
        String stc = console.nextLine();

        switch (stc){
            case "S":
                Student student = new Student();
                student.makeChoice();
                break;
            case "T":
                Teacher teacher = new Teacher();
                teacher.makeChoice();
                break;
            case "C":
                College college = new College();
                college.makeChoice();
                break;
            default:
                System.out.println("Invalid");
                makeChoice();
        }
    }
}

Second class to store values

public class StudentInformation {

    String name;
    String grade;
}

This is my service class where I've the problem. While running the method printStudent(); of this class i get following error: Exception in thread "main" java.lang.NullPointerException at STCAssignment.Student.printStudent(Student.java:76) at STCAssignment.Student.makeChoice(Student.java:31) at STCAssignment.Student.addStudent(Student.java:66) at STCAssignment.Student.makeChoice(Student.java:28) at STCAssignment.JavaMethod.makeChoice(JavaMethod.java:25) at STCAssignment.JavaMethod.main(JavaMethod.java:12) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

public class Student {

    int i =0;
    StudentInformation[] studentInformation = new StudentInformation[0];



    int makeChoice(){
        Scanner console = new Scanner(System.in);
        i = i +1;
        studentInformation = new StudentInformation[i];

        System.out.println("Do you want to continue(Y/N");
        String yesNo = console.nextLine();

        if (yesNo.equalsIgnoreCase("Y")){
            System.out.println("Add or Print(A/P)");

            String addPrint = console.nextLine();

            if (addPrint.equalsIgnoreCase("A")){
                addStudent();

            } else if (addPrint.equalsIgnoreCase("P")){
                printStudent();

            } else {
                System.out.println("Invalid");
                makeChoice();
            }

        }else if (yesNo.equalsIgnoreCase("N")){
             System.exit(0);
        } else {
            System.out.println("Invalid");
            makeChoice();
        }

        return i;

    }

    public void addStudent(){
        int i = 0;

        StudentInformation info = new StudentInformation();
        Scanner console = new Scanner(System.in);

        System.out.println("Enter Students name");
        info.name = console.nextLine();
        studentInformation[i]=info;


        System.out.println("Enter Students grade");
        info.grade = console.nextLine();
        studentInformation[i]=info;

        i = i + 1;
        makeChoice();
    }

    public void printStudent(){

        for (int j =0; j<studentInformation.length; j++){
            StudentInformation info = studentInformation[j];

            System.out.println("Student name:"+info.name);
            System.out.println("Student grade:"+info.grade);
        }

        makeChoice();
    }
}

How to solve it?

WonderWorld
  • 962
  • 1
  • 8
  • 16
AdityaKarki
  • 43
  • 11
  • 1
    This is unrelated to your NPE, but your code looks to be potentially way off track. For instance a Student class should have no input-output code in it nor the array that you've given it. Instead shouldn't it contain data pertaining to one Student such as name, registration number, etc... Please post your assignment requirements because I fear that you will want to throw this code out and re-start. – Hovercraft Full Of Eels Feb 13 '14 at 16:32
  • 1
    Look at line 76 of the Student class and see what could be null there. – GriffeyDog Feb 13 '14 at 16:32
  • 1
    Yes it points to ` System.out.println("Student name:"+info.name);` this part of method printStudent(), I could not figure it out. – AdityaKarki Feb 13 '14 at 16:35
  • @HovercraftFullOfEels Actually my teacher has asked to: 1. take input choice Student, Teacher or College information to add. 2. then as do you want to continue (y/n), again taking input. 3. Again take input asking Do you want to add or print in any of student, college or teacher. 4. after add or print again ask Do you want to continue (y/n). – AdityaKarki Feb 13 '14 at 16:37
  • @AdityaKarki: your comment above still doesn't justify your current code. Please consider posting the actual requirement. The I/O should be in your main method, not the Student class. I still suspect that you are ***way*** off base here. I don't think you'll regret showing this information to us. – Hovercraft Full Of Eels Feb 13 '14 at 16:38
  • @HovercraftFullOfEels sorry pressed enter so I've edited the above and posted what my tutor asked me to do. – AdityaKarki Feb 13 '14 at 16:40
  • info = studentInformation[j] == null, this is the cause. – Alexei Kaigorodov Feb 13 '14 at 16:43
  • Yep your code is most certainly off. – Hovercraft Full Of Eels Feb 13 '14 at 16:46
  • 2
    You are *replacing* the array each time, which means you are discarding previous values here `studentInformation = new StudentInformation[i];` – Peter Lawrey Feb 13 '14 at 16:47

4 Answers4

1

Since String name is null, it will throw a NPE if you try to use it before it has been initialized. It is likely for a user to be able to first print a student's information before "making" a Student. You instantiate a Student object, but don't assign a value to name in printing and since that is the first thing you print, it throws an NPE before it gets to the rest of your printing code. You could put a check in there to see if name or any of the other fields of your class are null before printing or trying to print anything.

You also are instantiating an empty StudentInformation class first and then creating another one. So two StudentInformation objects may be empty.

Here:

StudentInformation[] studentInformation = new StudentInformation[0];

and

here:

Scanner console = new Scanner(System.in);
i = i +1;
studentInformation = new StudentInformation[i];
Brian
  • 2,999
  • 4
  • 25
  • 47
1

After reading your instructions:

  1. take input choice Student, Teacher or College information to add.
  2. then as do you want to continue (y/n), again taking input.
  3. Again take input asking Do you want to add or print in any of student, college or teacher.
  4. after add or print again ask Do you want to continue (y/n).

I stand by my prior comments, that your code is way off base. I suggest that you:

  1. Create a Student class that is designed to hold a single Student's information, his name, perhaps an id number, grades, or whatever else is needed.
  2. Give it a constructor to pass this info into the class.
  3. give it getter methods and perhaps setter methods.
  4. Do not give it a StudentInformation array or any fields that don't pertain to a single Student.
  5. Do all the input output and use of Scanner in your Driver class, the one with the main method.

  • Perhaps your StudentInformation class should be renamed Student.
  • Your driver class, then one interacting with the user should probably have a List<Student> that is intialized as an ArrayList<Student>. It should likely have a similar List for Teachers.
  • Your Student class should not have an array that holds information about other students, which your current code does.
  • Your current code recreates a new Student class, which recreates its array each time its run, so any previous information stored in the array is lost, that's not going to work.
  • Again, you should start over.
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
1

Each time you create a new StudentInformation[i] you override the last student information array, but you don't copy its values.

This means the after the first makeChoice() your studentInformation variable will contain:

[StudentInformation<--some data-->]

After the second call to makeChoice() it will contain:

[null, StudentInformation<--new data-->]

After the tenth call is will look like:

[null, null, null, null, null,...,StudentInformation<--some new data-->]

Then, when you print it, it will cause an NLE.

Uri Agassi
  • 35,245
  • 12
  • 68
  • 90
0

Check to see if info.name or info.grade could be the null pointers:

if (info != null) {
    System.out.println("Student name:"+info.name);
    System.out.println("Student grade:"+info.grade);
} else System.out.println("Student information is null.");

Another possibility is that name and grade were not initialized. Make sure you do that for all the objects of StudentInformation, e.g. set them as default values when they are declared.

La-comadreja
  • 5,161
  • 8
  • 31
  • 59