I am writing a project to make class results.I have gotten this far but I am getting a NullPointer Exception.
I have commented the code well enough to understand.
/** * To generate examination result * * @author (your name) * @version (a version number or a date) */ // Declare packages to be imported import java.io.*;
public class Result { // instance variables int rollNumber; String name; int marks[]; int totalMarks; float aggPercentage;
// for reading users input InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr);
int i;
/** * Constructor for objects of class Result */ public Result() { // initialise instance variables rollNumber = 0; name = ""; marks = new int[10]; totalMarks = 0; aggPercentage = 0.0F;
}
/** * Method to input data * * @param nothing * @return nothing */ public void inputData() { try { System.out.println("Enter the information requested:"); System.out.println("--------------------------------");
System.o ut.print("Roll Number : "); rollNumber = Integer.parseInt(br.readLine());
System.out.print("Name : "); name = br.readLine();
for (i = 0; i < 2; i++) { System.out.print("Subject "+(i+1)+" : "); marks[i+1] = Integer.parseInt(br.readLine()); } // end of for loop
} // end of try
catch (IOException ioe) { System.out.println("Error is : "+ioe.toString()); } // end of catch
System.out.println("Data that you have just entered"); System.out.println("--------------------------------"); System.out.p rintln("Roll Number : "+ rollNumber); System.out.println("Name : "+ name);
for (i = 0; i < 2; i++) { System.out.println("Subject "+(i+1)+" : "+marks[i+1]); } // end of for loop
} // end of inputData() method
public static void main (String args[]) { Result Class8C[] = new Result[10]; Class8C[1].inputData(); // I am gettin NullPointerException here
// if I used the code below, it works okay // Result Class8C = new Result(); // Class8C.inputData(); // but I want to input data for 10 students
} // end main
} // end of class
Since I am new to Java, I would appreciate if someone could provide *solid* guidance, like maybe writing a bit of code or correcting the above so that it works.
you need to initialize your arrays before you use them for your benefit! Result Class8C[] = new Result[10]; By doing this you have only declared an intention that you will need this and that space for your array.
First, initialize with the following codes: for(int i = 0; i < 10; i++){ Class8C[i] = new Result(); } [/code
Now you are ready to get something out of them. To ask the user 10 times, you call a loop: [code] for(int j = 0; j < 10; j++){ Class8C[j].inputData(); }