Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Returning an array from a method to main

Would be glad if someone can help me with the following problem. The following method is suppose to returns an array whose ith entry is the number of times the int i appeared in array a. The method name gives the use of this method. Drawing a histogram of data found in array a.

    public static int histogram(int M, int[] a){

        int[] b = new int[M];

        for (int i = 0; i < M; i++){

           int w = 0; 

            for (int j = 0; j < a.length; j++){ 

            if (a[j] == i){ 
            w++;
            }
        }

           b[i] = w; 

     }

   return b; 
}

Accoring to me the code is correct - it may be wrong - I can't test it because I've got an error thats really bugging me.

Histogram.java:22: incompatible types found : int[] required: int return b;

1) What does above mean?? On example on the internet and in my handbook they also only use "return b;" to return an array to the main program.

2) How exactly does the return function work? Will I be able to use the following code to print the values of array b? Because at the moment I get an error as well for array b not being initialised in main... I think the error will go away if error 1 is sorted out. I'm new to JAVA so I won't really know - new to programming too.

for (int x = 0; x < M; x++){

        System.out.printf("%d ", b[x]);

     }`

3) Should I maybe print the values in the histogram() method? The question to answer is though to "return" the array with the histogram values in it.

Would really be glad if you can help...

If you've come this far - thanks a lot... Even just reading till here means a lot :)

like image 257
ISJ Avatar asked May 10 '26 05:05

ISJ


2 Answers

You should try returning array of ints instead of a single integer

public static int[] histogram ...

I'm not sure about 2&3, though.

2) return is not a function, it's a keyword causing you to leave the method.
3) You can, if you want to.

edit
Whatever variables you declared in histogram method stay there, they're local. If you want some variable in the main method, declare it. E.g.,

int[] b = histogram(param1, param2);
like image 154
Nikita Rybak Avatar answered May 11 '26 19:05

Nikita Rybak


2.) your main should have something like:

int[] b = histogram(M, a);

3.)No it's better how you have it I think -- keep the input/output stuff in main and just keep your histogram construction stuff by itself in the histogram method.

like image 43
Dave L. Avatar answered May 11 '26 19:05

Dave L.