0

This code finds the frequency of elements in the array. But it is showing cannot read field because array is null.

Code

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner lta = new Scanner(System.in);
        Count[] arr = new Count[101];
        System.out.println("Enter the elements :");
        for (int i = 0;i < 10;i++){
            int value = lta.nextInt();
            arr[value].count += 1;
        }
        System.out.println("Frequency of the elements in the array :");
        for (int i = 1;i < arr.length;i++){
            if (arr[i].count > 0){
                System.out.print(i + " : " + arr[i].count);
                System.out.println();
            }
        }
    }
    static class Count{
        long value;
        long count;
    }
}


Error

Exception in thread "main" java.lang.NullPointerException: Cannot read field "count" because "arr[value]" is null

Is there any solution for this program to run without any error or what is the reason behind termination of the JAVA program.

2 Answers2

1

You are only populating the first 10 elements but reading the first 101 elements. arr.length is 101 because arr = new Count[101].

Your read loop, like the write loop, needs to stop at i < 10

John Williams
  • 4,252
  • 2
  • 9
  • 18
1

arr[i].count is attempting to access a field called count in the object at the array index of i. You've initialized the array, but it is empty. You can check this with a simple print of the array[0], which will return null.

To fix this, initialize the element of the array before you try to access it.

for (int i = 0 ; i < 10 ; i++){
  int value = lta.nextInt();
  arr[value] = new Count();
  arr[value].count += 1;
}

Note however, that this will break the next loop. This is because you only initialize 10 indices in the array, but attempt to access all 102 of them.

Generally it's a bad programming practice to initialize a, array larger than what you need. If you plan to only allow 10 values to be input, than initialize your array to 10. Then use the length of the array in both loops.

tbatch
  • 1,398
  • 10
  • 21