import java.lang.*; import java.util.Scanner; class Casio { String abc[]; Scanner j = new Scanner(System.in); public Casio(int x) { System.out.println("IM IN DEFAULT CONSTRUCTOR"); String abc[] = new String[x]; for(int i=0;i<x;i++) { System.out.println("ENTER THE NAME OF FRIEND "+(i+1)); abc[i]= j.nextLine(); } } public void show(int q) { for(int ji=0;ji<q;ji++) { System.out.println("THE NAMES ARE : "+(abc[ji]));//<-- Error at Line number 27 } } } public class mycode { public static void main(String args []) { int n,q; Scanner s = new Scanner(System.in); System.out.println("ENTER INITIALIZATION VALUE"); n = s.nextInt(); q=n; Casio obj = new Casio(n); obj.show(q);//<-- Error at line number 43 } }
THE OUTPUT I GET IS:
Exception in thread “main” java.lang.NullPointerException
at clg.Casio.show(mycode.java:27)
at clg.mycode.main(mycode.java:43)
What I have tried:
When i execute the program . It takes input but it fails to show output. I am trying to take input from array and display output by method calling. please help me. Thank you
——
The Casio constructor creates a local array called “abc” which “hides” the class level version. As a result, the class level version never gets any values assigned to it, or indeed any space for elements.
Change this line:
Hide Copy Code
String abc[] = new String[x];
To this:
Hide Copy Code
abc = new String[x];
And try again.
Seriously, you would have found this very, very quickly if you had used the debugger … it should be your first port of call when you have runtime problems.
发表回复