1

I am currently having to write a method that takes in two parameters: an array of integers called data and an integer called num. The purpose of this method is to count the amount of times that number shows up in the array. I am having trouble figuring out how to declare the array in the method. I was wondering if there was any easier way that I did below:

Method

public static void countNumbers( int data[], int num ) {
        int count = 0;

        for(int i = 0; i < data.length; i++) {
            if(data[i] == num)
                count++;
        }
        if (count == 0)
            System.out.println("There are no " + num + "'s in the array.");
        if (count == 1)
            System.out.println("There is one " + num + " in the array.");
        if (count > 1)
            System.out.println("There are: " + count + " " + num + "'s in the array.");
}

Main Class

public static void main(String args[]) {
        int firstArray[] = {1,2,3,4,5};
        Methods.countNumbers(firstArray, 2);
    }

So I was wondering if you could directly declare the array within the countNumbers(data,num) any help would be appreciated!

4
  • 1
    I don't understand your question -- you declare the array in the method parameter and appear to do so appropriately. So what is this all about? What confuses you. Commented Apr 7, 2017 at 1:05
  • I was wondering if there was any way to declare the array within the method such as: Methods.countNumbers(int firstArray[] = {1,2,3} , 2); Commented Apr 7, 2017 at 1:07
  • If you don't reference it anywhere else (you don't need it anywhere else) just do Methods.countNumbers({1, 2, 3}, 2) Commented Apr 7, 2017 at 1:13
  • @MCMastery I don't think that's going to compile. Commented Apr 7, 2017 at 1:14

1 Answer 1

3

Is that what you are looking for?

public static void main(String args[]) {
    Methods.countNumbers(new int[] {1,2,3,4,5}, 2);
}
Sign up to request clarification or add additional context in comments.

2 Comments

This was exactly what I was looking for, thank you very much. I can not accept an answer just yet though!
Ha, glad I could be of help. And don't worry, you can always come back once you've got more rep. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.