在此交互式程序中,您将找到一个菜单,其中包含用于在阵列上执行不同功能的选项。该数组取自名为“data.txt”的文件。该文件包含整数,每行一个。显然,我没有包含整个代码(它太长了)。但是,我希望有人可以帮我解决在数组中找到素数的问题现在,控制台打印了素数的数组地址([I @ 4a13ccea])。欢迎任何建议。我的计划的一部分如下。感谢。
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu3(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
for (int j = 0; j < i; ++j) {
System.out.print("The numbers in the file are: " + numbers[j] + " ");
}
}
public static boolean prime(int x) {
boolean answer = true;
for (int i = 2; i <= x / 2; i = i + 1) {
if (i != x) {
if (i % x == 0) {
answer = false;
}
}
}
return answer;
}
public static int[] primes(int[] numbers) {
int primesCount = 0;
for (int i : numbers) {
if (prime(i)) {
primesCount = (primesCount + 1);
}
}
if (primesCount == 0) {
return null;
}
int[] result = new int[primesCount];
int index = 0;
for (int i : numbers) {
if (prime(i)) {
result[index] = i;
index = index + 1;
}
}
return result;
}
}
答案 0 :(得分:1)
循环遍历数组并打印每个元素,或者如果格式符合您的需要,请使用java.util.Arrays.toString(int[])
方法。
答案 1 :(得分:0)
两个分数
如果您打印这样的数组,您将获得数组的地址,而不是内部。
System.out.println("The primes in the file are: " + primes(numbers));
将此行替换为迭代primes(numbers)
第二个是,在你的public static boolean prime(int x)
函数中,你有这一行
for (int i = 2; i <= x / 2; i = i + 1)
虽然这有效,但要找到一个素数哟不需要迭代直到 x / 2 。对于性能优势 x的平方根更适合。