我正在阅读有关Java中数组的信息,并编写了一个代码来计算数组中所有数字的出现次数。
public class Example {
static int b[] = new int[13]; // I can not do static int b[] = new int[a.length] because a[] in not static array
static int count = 0;
public static void main(String[] args) {
int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
counting(a);
printCount();
}
private static void printCount() {
int k = 0;
for (int i = 0; i < b.length; i++) {
System.out.print("number" + " " + a[k] + " " + "is found" + " "); // here I get error in a[k] because it is not static , eclipse says : a cannot be resolved to a variable
System.out.println(b[i] + " " + "times");
k++;
}
System.out.println();
}
private static void counting(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a.length; k++) {
if (a[i] == a[k]) {
b[i] = ++count;
}
}
count = 0;
}
}
}
我陷入了我的printCount()方法中,在该方法中我无法调用a []数组,因为a []在main方法中不是静态的。
我试图在主方法中编写
static int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
,但是eclipse不接受。如何使a []成为静态数组,以便可以在上述Example类中的所有方法中实现?
谢谢
最佳答案
public static void main(String[] args) {
int[] a = { 2, 3, 4, 3, 3, 5, 4, 10, 9, 1, 9, 11, 15 };
counting(a);
printCount(a);
}
在printCount()方法中传递数组。