Results 1 to 2 of 2
  1. #1
    mathias is offline Member
    Join Date
    Jul 2007
    Posts
    40
    Rep Power
    0

    Default ERROR: nullPointerException

    Hi, Please check this
    Java Code:
    import TerminalIO.KeyboardReader;
    
    public class manyStudents {
    	public static void main (String [] args) {
    		KeyboardReader 	reader 	= new KeyboardReader();
    		Student[] 		student = new Student[500];
    		int 			stuNumb = reader.readInt ("Enter the number of students (max is 500): ");
    		
    		for (int i = 0; i < stuNumb; i++) {
    			String stuName = reader.readLine ("Enter the name of sutden #"+ (i+1) +": ");
    			student[i].setName(stuName);
    			int testNumb = reader.readInt ("Enter the number of tests for "+ student[i].getName() +": ");
    		}
    	}
    }
    This code gives me a null pointer exception at line 11...
    why? how can i fix it?
    Thanks

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    Student[] students = new Student[500];
    // All elements of this array are null.
    for(int j = 0; j < 10; j++)
        System.out.println("students["+j+"] = " + students[j]);
    // If the Student class has a no-argument constructor you could
    // instantiate them all at once:
    for(int j = 0; j < stuNumb; j++)
        students[j] = new Student();
    // You could also instantiate a student for each new element as you go:
    for (int i = 0; i < stuNumb; i++) {
        String stuName = reader.readLine ("Enter the name of sutden #"+
                                           (i+1) +": ");
        students[i] = new Student();
        // Now we have a non-null array element to work with.
        students[i].setName(stuName);
        int testNumb = reader.readInt ("Enter the number of tests for "+
                                        students[i].getName() +": ");
    }

Similar Threads

  1. NullPointerException
    By ravian in forum New To Java
    Replies: 2
    Last Post: 12-07-2007, 05:20 PM
  2. NullPointerException
    By Feng in forum New To Java
    Replies: 5
    Last Post: 11-24-2007, 08:51 PM
  3. NullPointerException problem
    By warship in forum AWT / Swing
    Replies: 5
    Last Post: 08-10-2007, 05:43 PM
  4. ERROR: nullPointerException in applet
    By barney in forum Java Applets
    Replies: 1
    Last Post: 08-07-2007, 08:11 AM
  5. Replies: 2
    Last Post: 07-02-2007, 03:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •