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 🙂
You should try returning array of ints instead of a single integer
I’m not sure about 2&3, though.
2)
returnis 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
histogrammethod stay there, they’re local. If you want some variable in themainmethod, declare it. E.g.,