I am trying to create a custom class Student, which contains 2 fields, Name and Marks. I read on the internet that I need Getters & Setters to do so. So, I wrote the following code but it is giving me a NullPointerException.
import java.util.*;
class Student
{
public String name;
public int marks;
public int getMarks()
{
return this.marks;
}
public void setMarks(int marks)
{
this.marks = marks;
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
}
public class getterSetter
{
public static void main(String[] ab)
{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int x;
Student[] student = new Student[n];
String[] inputs = new String[n];
s.nextLine();
for(int i = 0; i < n; i++)
{
String xx = s.nextLine();
inputs[i] = xx;
}
for(int i = 0; i < n; i++)
{
String[] words = inputs[i].split("\\s+");
student[i].setName(words[0]);
student[i].setMarks(Integer.parseInt(words[1]) + Integer.parseInt(words[2]) + Integer.parseInt(words[3]));
}
for(int i = 0; i < n; i++)
{
System.out.println(student[i].getName());
System.out.println(student[i].getMarks());
}
}
}
The console screen is :
java getterSetter
3
abc 10 10 10
def 10 10 10
ghi 10 10 10
Exception in thread "main" java.lang.NullPointerException
at getterSetter.main(getterSetter.java:58)