-1

I am writing a program that will take several numbers and display them in ascending order and then descending order. When I try to assign the input to the array, I get a null pointer exception and I am not sure why. Any help would be appreciated.

Here is my code:

static int[] numbers;
public static void main(String[] args) {
    int i=0;        
    while(i<50)
    {            

        String input = JOptionPane.showInputDialog("Enter any number or type X to exit");
        System.out.println(input);
        if(input.equals("X"))
        {
            break;
        }
        numbers[i]=Integer.parseInt(input);//This is where i get the exception          
        i++;
    }
Bob Suko
  • 13
  • 3

1 Answers1

0

You haven't instantiated numbers. You need to do:

numbers = new int[50];

at the start of your method.

However, you'd actually be better off using an ArrayList<Integer> which allows for dynamic resizing, rather than a fixed size array. You would do:

List<Integer> numbers = new ArrayList<Integer>();
...
numbers.add(Integer.parseInt(input));

This won't then cause issues if you add more than 50 numbers into the array, which a fixed size array would.

Andy Brown
  • 18,961
  • 3
  • 52
  • 62