0

I am trying to print out a simple code but I do not seem to be able to pass the array variable of the method. Sorry if it is something obvious, I am only starting with Java. I am getting the "The method asd in the type MyClass is not applicable for the arguments (int,int,int,int)

public int asd(int[] nums) {
      int count = 0;
      // Note: iterate to length-1, so can use i+1 in the loop
      for (int i=0; i < (nums.length-1); i++) {
        if (nums[i] == 6) {
          if (nums[i+1] == 6 || nums[i+1] == 7) {
            count++;
          }
        }
      }
      return count;
    }

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println(asd(1,22,3,4,2,2,2));

}
1
  • 1
    I'm not sure why this was never mentioned, but you can declare a variadic argument function by making it look like this: public int asd(int... nums) { The ... can only be on the last argument in a method declaration as it collects all arguments after that one into an array. Commented Oct 8, 2024 at 3:04

2 Answers 2

5

The method asd is expecting a single parameter of type int []. You are attempting to pass each integer as a separate parameter (resulting in seven parameters , 1,22,3,4,2,2,2).

To correct the compiler-error you can enclose the parameter values in {} and prefix it with new int[] to create an Array literal:

 System.out.println(asd(new int[] {1,22,3,4,2,2,2}));
Sign up to request clarification or add additional context in comments.

1 Comment

I will give you the answar, wait for me. :)
-1

you can try this

public static void main(String[] args) {
    int []arr={1,22,3,4,2,2,2}; //this is array literal
    System.out.println(asd(arr));
}

The above program will give compilation error attaching screenshot below

enter image description here

15 Comments

not really different then the previous (5 year old) answer, is it? But for much less explanation (none!)
It will give compilation error, in any IDE. And why I gave a new answar because where is code reusability?
1) which compilation error? It is valid Java (if we ignore that asd is not static); 2) what do you mean with "* code reusability*"? How is that relevant, does that apply here?
I have added the screenshot see the error, and for code reusablity we have to discuss and I dont have time for it figure it out. I just copy and paste the code.
(And if you don't have time to post a proper answer ... on an old question ... then the solution is don't post an answer at all.)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.