Search code examples
javaintellij-ideainteger

Can I print the whole array without getting 'Cannot read field "value" because "anotherInteger" is null' error?


Well I am trying to create a program that is going to print number is decending number usings rays.sort(array, Collections.reverseOrder()); method.

it's giving me an error. because some of the values of the array is NULL. error msg -Exception in thread "main" java.lang.NullPointerException: Cannot read field "value" because "anotherInteger" is null

Example: If I put 5 as the value of number, then only the first 5 elements of that array is going to have a value. So, it's showing me an error.

and here is the code

            int number = sc.nextInt();
            Integer array[]= new Integer[10];
            for(int j=0;j<number;j++){  // here number is the number of inputs,
                    array[j]= sc.nextInt();
            }
            Arrays.sort(array, Collections.reverseOrder()); // to sort our array
            System.out.println(Arrays.toString(array));

now, is there any way that I can print the whole array without getting the error message?


Solution

  • Solution:

    int numbersAmount = sc.nextInt();
    Integer[] array = new Integer[numbersAmount];
    for(int j = 0; j < array.length; j++){
        array[j] = sc.nextInt();
    }
    Arrays.sort(array, Collections.reverseOrder());
    System.out.println(Arrays.toString(array));
    

    Additionally:

    Think about:

    • What if you press ENTER without any Input?
    • What If you press ENTER If the input is an alphabetic letter?