-1

Basically the aim of this problem is to count the number of times the number 9 is typed in the array, for example, arrayCountNines([1, 9, 9, 3, 9]) = 3

I have tried doing a Stream of the numbers, for example by using .collect but that didn't seem to work. Also tried HashMaps

    public class NewClass4 {
   public int arrayCountNines(int[] nums) {
      HashMap < Character, Integer > map = new HashMap<>();
      for (int i =0; i<nums.length; i++) {
          char[] charr = String.valueOf(nums[i]).toCharArray(); 
          for(int j = 0; j<charr.length; j++) {
              if(map.containsKey(charr[j])) {
                  map.put(charr[j], map.get(charr[j])+1); 
              }
              else {
                  map.put(charr[j], 1);
              }
          }
      }
      return 1; 

}


    }

]1

It doesn't return the number of times 9 is in the array

Ezequiel
  • 3,477
  • 1
  • 20
  • 28
Bob29
  • 11
  • 1
  • 4
  • 3
    maybe it should `return`something different from `1`. What bother me is that there is absolutly no `9`in your code – jhamon Sep 24 '19 at 13:41

4 Answers4

2
public int arrayCountNines(int[] nums) {
   return (int) Arrays.stream(nums).filter(value -> value == 9).count();
}
Robert Freese
  • 71
  • 1
  • 1
  • 4
1

Try this simple approach:

public int arrayCountNines(int[] nums) {
    int result = 0;
    for(int i = 0; i < nums.length; i++){
        if(nums[i] == 9){
            result++;
        }
    }
    return result;
}
GitPhilter
  • 171
  • 9
0

Try that:

   public int arrayCountNines(int[] nums) {
      int count=0;
      for (int i =0; i<nums.length; i++) {
          int v = nums[i];
          if (v==9) {
             count++;
          }
      }
      return count; 
   }
Deian
  • 1,237
  • 15
  • 31
0

Can't you just iterate through the array using a for-loop and then add to a counter whenever the item is equal to 9?

...
int nineCounter = 0;
for(int i=0; i<array.length ; i++){
  if(array[i] == 9){
    nineCounter++;
  }
}
return nineCounter;
Ben
  • 62
  • 1
  • 8