I have a problem putting input data from the user inside an array. The program should fill these arrays and show me the desired student. Here's the code:
package sorting.test;
import java.util.*;
public class SortingTest {
String name;
int grade;
public SortingTest (String name, int grade) {
this.name=name;
this.grade=grade;
}
public String getname() { \\<
return name; \\<
}
public int getgrade() { \\<-- Are these returns necessary?
return grade; \\<
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Total students: ");
int n,i;
n=in.nextInt();
SortingTest [] x = new SortingTest [n];
for (i=1;i<=n;i++) {
System.out.println("Student "+i);
x[i].name=in.next(); //Gives an error when I try to put an input
x[i].grade=in.nextInt();
}
System.out.println("Show infos of student: ");
i=in.nextInt();
System.out.println(x[i].name +" " +x[i].grade);
}
}
In another program I solved this problem by just doing this
x[i].something=in.nextType();
to
something=in.nextType();
x[i]=new ArrayType (x);
It doesn't seem to work here. The error that I got after writing the name is
Exception in thread "main" java.lang.NullPointerException
at sorting.test.SortingTest.main(SortingTest.java:24)
C:\Users\Anthony\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 10 seconds)
Also I wanted to know if these returns that I marked are necessary, I can't understand their usefulness, just following my professor examples.
Comments
Post a Comment