gpt4 book ai didi

java - 如何在java中的main方法中创建一个静态数组?

转载 作者:行者123 更新时间:2023-11-29 10:10:34 25 4
gpt4 key购买 nike

我在阅读 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[] 成为一个静态数组,以便在我上面的示例类中的所有方法中都可以访问它?

谢谢

最佳答案

 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() 方法中传递数组。

关于java - 如何在java中的main方法中创建一个静态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37578291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com