-2

Given an array of numbers, I have to return the number of times that 9 appears in the array. I created a new array, where I added all the 9s from the original array. But at the end when I want to return the length of the new array, I get an error "cannot find symbol length". I know that in this case, length is an attribute, not a method, so that's not the problem. I even used the length attribute in the for loop and it doesn't seem to be a problem (because the error occurs at line 8). This is starting to become frustrating. If anyone knows what the reason for this is, please let me know.

public int arrayCount9(int[] nums) {
    ArrayList<Integer> array = new ArrayList<Integer>();
    for (int i = 0; i < nums.length; i++){
        if (nums[i] == 9){
            array.add(nums[i]);
        }
    }
    int len = array.length;
    return len;
}
QBrute
  • 4,405
  • 6
  • 34
  • 40
Sebastjan
  • 71
  • 1
  • 2
  • 8

2 Answers2

0

You need to use the method size() for collection class ArrayList.

HaroldSer
  • 2,025
  • 2
  • 12
  • 23
0

An ArrayList<Integer> isn't the same as an Integer[] but you're using the same variable as in an array to get the size of the list.

An ArrayList<Integer> has a method called ArrayList#size() instead of a variable called length to get the size of the list.

Julian
  • 837
  • 1
  • 11
  • 24