RequiemDream
RequiemDream

Reputation: 31

Exception in thread "main" java.lang.NumberFormatException: null

I have tried everything I possibly could with this, but I still could not find any solution to this, and here is the error, I tried to change the null in line 16, etc but to no avail, and I'm a new Java programmer so I do not have much experience using this language, all help appreciated!

Exception in thread "main" java.lang.NumberFormatException: null at java.lang.Integer.parseInt(Integer.java:454) at java.lang.Integer.parseInt(Integer.java:527) at DebugEight4.main(DebugEight4.java:11)

import javax.swing.*;
public class DebugEight4
{
 public static void main(String[] args) 
{
  int x = 0, y;
  String array[] = new String[100];
  String entry;
  int i = Integer.parseInt(array[1]);
  final String STOP = "XXX";
  StringBuffer message = new
      StringBuffer("The words in reverse order are\n");

  entry = JOptionPane.showInputDialog(null,
    "Enter any word\n" +
    "Enter " + STOP + " when you want to stop"); 
  while(!(entry.equals(STOP)))
  {
     array[x] = entry;
     x++;
     entry = JOptionPane.showInputDialog(null,
        "Enter another word\n" +
        "Enter " + x + " when you want to stop"); 
  }
  for(y = 0; y > 0; ++y)
  {
     message.append(array[y]);
     message.append("\n");
  }
  JOptionPane.showMessageDialog(null, message);
 }
}

Upvotes: 1

Views: 14741

Answers (2)

Mengjun
Mengjun

Reputation: 3197

The error is caused by the following code:

 int i = Integer.parseInt(array[1]);

In your code, you just declare the String array as below. But all of the element is null in array.

 String array[] = new String[100];

Please initizlize them first.

Actually, variable i is not used in the context, so just remove the code "int i = Integer.parseInt(array[1]);".

And I do not think the following code for for-loop is correct. The only way to stop it is that the index exceed the range of array.

for(y = 0; y > 0; ++y)
{
 message.append(array[y]);
 message.append("\n");
}

Upvotes: 0

Preet Sangha
Preet Sangha

Reputation: 65496

There is nothing in the array except empty strings.

  String array[] = new String[100];
  //...
  int i = Integer.parseInt(array[1]);

an empty string cannot be parsed into an Integer.

For example:

  String array[] = new String[100];     <<-- Create an array of empty string
  array[1] = "1";                       <<-- set second item in array to a parseable value
  int i = Integer.parseInt(array[1]);   <<-- Parse the value out

Upvotes: 1

Related Questions