+ 1

Java Runtime Error

I am new to Java. I am trying to use objects as array but it is showing a runtime error as " Null pointer exception". This is my code : import java.util.*; class Students { String name; int id; double ptr; public void show() { System.out.println("ID : " + id + "Name : " + name + "Pointer " + ptr); } } public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Students s[] = new Students[4]; System.out.print("Enter name : "); s[0].name = sc.nextLine(); System.out.print("Enter ID number : "); s[0].id = sc.nextInt(); System.out.print("Enter Pointer of the student : "); s[0].ptr = sc.nextDouble(); System.out.println(s[0].name); } }

6th Sep 2019, 5:27 PM
Prathamesh Ramane
Prathamesh Ramane - avatar
2 Respuestas
+ 4
Students[] s = new Students[4]; //every index in s is null //so here we create the objects for(int i=0;i<s.length;i++){ s[i] = new Students(); }
6th Sep 2019, 6:03 PM
Anton Böhler
Anton Böhler - avatar
+ 6
You didn't obtain a memory for objects you just reversed 4 pointer to Students like Students a1,a2,a3,a4; each on is pointing to nu you have to add this for(int i=0;i<4;i++) d[i]=new Students();
6th Sep 2019, 5:56 PM
ABADA S
ABADA S - avatar