【发布时间】:2015-05-10 10:22:47
【问题描述】:
我想创建一个程序,要求用户使用数组输入 5 个整数并确定输入的所有素数。但我有困难。似乎是什么问题?我为此使用 JCreator。
import java.util.Scanner;
public class PrimeNumbers{
public static void main (String[] args){
int[] array = new int [5];
Scanner in = new Scanner (System.in);
System.out.println("Enter the elements of the array: ");
for(int i=0; i<5; i++)
{
array[i] = in.nextInt();
}
//loop through the numbers one by one
for(int i=0; i<array.length; i++){
boolean isPrime = true;
//check to see if the numbers are prime
for (int j=2; j<array[i]; j++){
if(array[i]%j==0){
isPrime = false;
break;
}
}
//print the number
if(isPrime)
System.out.println(array[i] + " are the prime numbers in the array ");
}
}
}
【问题讨论】:
-
您能否详细说明您的问题是什么。
-
我希望输出是这样的:输入数组的元素——23 98 45 101 6 数组中所有的素数都是——23 101
-
但它给了我 0 1 2 3 作为输出。
-
请edit您的问题并在此处而不是在 cmets 中添加此信息。
-
只是对已经建议的答案的改进:为了测试数字 (n) 是否为素数,您可以检查该数字是否可以被 2 到 SquareRoot(n) 之间的任何数字整除。无需使用小于 n 的所有数字对其进行测试。利用该因素的示例实现。 davidsekar.com/algorithms/sieve-of-eratosthenes-prime