gpt4 book ai didi

java - 将文件中的整数存储到数组中并查找素数 JAVA

转载 作者:行者123 更新时间:2023-12-01 14:47:08 26 4
gpt4 key购买 nike

在此交互式程序中,您将找到一个菜单,其中包含对阵列执行不同功能的选项。该数组取自名为“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;
}
}

最佳答案

循环遍历数组并打印每个元素,或者使用 java.util.Arrays.toString(int[]) 方法(如果其格式适合您的需要)。

关于java - 将文件中的整数存储到数组中并查找素数 JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316230/

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