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
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);
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.
Public static int[] // since the return is an array
I think you can call the method
histogram();
in the main method
and hope it will work.
when you are useing an array you shuld write it in a method of a class not in body of class
and also return is not a method or a function, it is just a keyword that we use in our methods
so write it in method and then compile it again!
精彩评论