在此交互式程序中,您將找到一個菜單,其中包含用於在陣列上執行不同功能的選項。該數組來自一個名爲「data.txt」的文件。該文件包含整數,每行一個。顯然,我沒有包括整個代碼(這太長了)。然而,我希望有人能夠幫助我解決在數組中找到素數的問題。現在,控制檯打印數組的素數地址([I @ 4a13ccea))。歡迎任何建議。我的部分程序如下。謝謝。將整數存儲到數組中,並查找素數JAVA
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;
}
}
也許你想返回'result [index]'而不是'result'。 – Maroun 2013-03-09 21:47:16
返回'result [index]'將我的方法返回類型更改爲'int'。我希望它返回'int []'。 – lancer 2013-03-09 21:49:52
您應循環'數字'併爲每次迭代打印'primes(數字)',但您應該返回'result [index]'而不是..(如果我沒有誤解您的話) – Maroun 2013-03-09 21:55:58