Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This code supposedly checks an array of integers for 9's and returns it's frequency but the method is not being recognized. Any help please to make this code work.

public static int arrayCount9(int[] nums) {
      int count = 0;
      for (int i=0; i<nums.length; i++) {
        if (nums[i] == 9) {
          count++;
        }
      }

      return count;
};


public static void main(String[]args){

    System.out.println(arrayCount9({1,2,9}));

}
share|improve this question
1  
In the future instead of just saying "it's not working", provide more detailed information - if you're getting an error message please provide it. If not then explain what led you to believe that it isn't working the way it should. –  Andrew_CS 38 mins ago

2 Answers 2

up vote 4 down vote accepted

Change your method call to the following:

System.out.println(arrayCount9(new int[]{1,2,9}));

Alternatively:

int[] a = {1,2,9};
System.out.println(arrayCount9(a));

The shortcut syntax {1,2,9} can only be used when initializing an array type. If you pass this notation to a method, it will not be interpreted it as an array by the compiler.

share|improve this answer
    
Why does that work? –  tbodt 40 mins ago
6  
Because you're not writing Javascript. –  Justin Jasmann 40 mins ago

Your method arrayCount9 is int type ,and must return int. System.out.prinln print only String.

Try this:

    System.out.println(arrayCount9({1,2,9})+"");

or

        System.out.println(arrayCount9({1,2,9}).toString());
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.