tokenizer and "Exception in thread "main" java.lang.NullPointerException" runtime error
I'm trying to tokenize a string and assign each token to a cell of array in java. this is my code to tokenize but I got following run-time error:
Exception in thread "main" java.lang.NullPointerException
this error is appeared at line 10.
can anybody help me to solve this error bye an example?????
#1 Scanner in = new Scanner(System.in);
#2 System.out.print("Enter your name: ");
#3 String name = in.nextLine();
#4 String a[]=null;
#5 int i=0;
#6 StringTokenizer tokenizer=new StringTokenizer(name开发者_高级运维," ");
#7 while (tokenizer.hasMoreTokens())
#8 {
#9 String token = tokenizer.nextToken();
#10 a[i]= token;
#11 i++;
#12 }
String a[]=null;
and you are doing
a[i]= token; // a is pointing to null, so a[i] will throw NPE, you need to initiate it
I think you aren't aware of size of array so go for List
make it
String a[]=null;
to
List<String> a = new ArrayList<String>();
and replace
a[i]= token;
i++;
to
a.add(token);
Also See
- List
Your String-Array is null. Create a new instance of the String-Array before you use it:
#1 Scanner in = new Scanner(System.in);
#2 System.out.print("Enter your name: ");
#3 String name = in.nextLine();
#4 String a[]; // removed '= null'
#5 int i=0;
#6 StringTokenizer tokenizer=new StringTokenizer(name," ");
#6.1 a[] = new String[tokenizer.countTokens()];
#7 while (tokenizer.hasMoreTokens())
#8 {
#9 String token = tokenizer.nextToken();
#10 a[i]= token;
#11 i++;
#12 }
for more see here: http://download.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html#countTokens()
An even easier solution would be to use an array list instead of an array. The advantage of an ArrayList is, that you can add values to the list and you don't have to specify a fixed size in the beginning, means the size is variable.
Example:
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
List<String> list = new ArrayList<String>();
StringTokenizer tokenizer=new StringTokenizer(name," ");
while (tokenizer.hasMoreTokens())
{
String token = tokenizer.nextToken();
list.add(token)
}
if you want to know now, how many elements are in the list use list.size()
String a[]=null;
null
assigned before processing, so NullPointerException
!
try
String[] a=new String[100];
or something;
Because you assign null
to the variable a
, when you later try to use that variable it will cause a NullPointerException
. You need to assign something meaningful to a
Here is the problem in your code:
String a[]=null
You initialize the array to NULL and then set its entries ... of course you get a NullPointerException.
You have to initialize your array with a member count, like String[] a = new String[10];
精彩评论