[英]Store ints into array from a file and find primes JAVA
在此交互式程序中,您將找到一個菜單,該菜單包含用於在陣列上執行不同功能的選項。 該數組取自名為“ 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[])
方法。
兩個標記
如果您這樣打印一個數組,您將獲得該數組的地址,而不是內部地址。
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)
盡管這可行,但要找到素數yo不需要迭代x / 2 。 為了提高性能,x的平方根會更適合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.