r/javahelp • u/rachit_dani • Jan 21 '20
Homework Fairly new to Java, help me with this code consisting of two classes.
I made an object of the class TestStudent and I want to store info of 5 students but the line 22 returns NullVariableException while scanning the name and id.
This is my code.
Please tell me some other way to achieve it if you can.
4
u/kOrupt3dd Jan 22 '20
Looks like everyone helped answer you question just a tip take advantage of java and try using S.length On your loops
For(int i = 0, i < s.length,I++)
3
u/chickenmeister Extreme Brewer Jan 21 '20
Object arrays are initially filled with null values. So before you can call s[i].insertInfo(name1,id1);, you would need to create a TestStudent object and store it at that position in the array. (e.g. s[i] = new TestStudent()).
2
u/arthurdent Jan 22 '20
Depending on your requirements, you may want to look into using an ArrayList instead of a primitive array. With an ArrayList you just specify what type of data it takes and then you can add individual objects to the list using a loop or something. You don't have to set a maximum size, either.
ArrayList students = new ArrayList<TestStudent>;
for (int i = 0; i < 5; i++) {
students.add(new TestStudent());
System.out.print("Enter the name of student " + (i+1) + " -> ");
students.get(i).name = sc.nextLine();
// etc...
}or something like that
17
u/Amakaphobie Jan 21 '20
this line initiates your array of students. now you have an array of students but its still empty. You need to initiate the studentObjects in your array too. To do that you need to call the actual studen constructor before first using your student object.
If you want to that (and you should) you need to call:
inbetween line 21 and 22.
a cleaner way would be to add a Constructor to your studen class like this:
with that you can simple replace your call
with