English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

Here's the code I have and it is giving a very stupid error! any idea why?

public class Main {


public Main() {
allStudents = new Stu[1];
allStudents[0].Name1 = "re"; //The NullPointerException occurs here
}
Stu[] allStudents;
public static void main(String[] args) {
new Main();
}
class Stu
{
String Name1;
String Address1;
String Nationality1;
String DOB1;
String Sex1;
int TelephoneNo;
int ID_nos;
int MobileNo;
int MarksEnglish;
int MarksMaths;
int MarksComputers;
}
}

2007-03-06 15:15:03 · 4 answers · asked by HellBoy 2 in Computers & Internet Programming & Design

4 answers

Although you have created an array to hold the students, you have not actually created a student object. Unlike simple data types, you must explicitly create an object data type.

public Main() {
allStudents = new Stu[1];
allStudents[0] = new Stu();
allStudents[0].Name1 = "re"; // no more null pointer here
}

2007-03-06 15:27:18 · answer #1 · answered by Math Guy 4 · 1 0

You declare the array, but don't put any objects in it

allStudents[0]= new Stu(); //right before the spot you got the null pointer

For that matter, do you really want an array? A Vector might be a better choice.

2007-03-06 15:56:26 · answer #2 · answered by Greg M 2 · 0 0

We have to allocate the memory individual elements of the array. If you give that no more errors will not be occurred there. And please define the students class outside of the Main class. Because this is not better of the good programmers.

2007-03-06 16:31:16 · answer #3 · answered by Anonymous · 0 0

I think the variables in a class are default to private, so to change them requires a method in the class.

2007-03-06 15:25:06 · answer #4 · answered by Tasm 6 · 0 1

fedest.com, questions and answers