[英]Output amount of primes in array
我是Java的新手,但不是很好。 对我来说,这是一个反复试验的过程。
我正在研究一个Java程序来输出数组中的素数。 我可以输出素数,但也要输出素数。 我试图将每个素数添加到标题为“素数”的数组列表中,然后在程序末尾返回“ primes.size()”。 它没有按预期工作。 计数实际上是关闭的。 当我创建一个由5个数字组成的数组时,它输出3个质数,2、3和5。但是然后它说我有4个质数。 我认为可能将1算作素数。 因为当我创建一个由20组成的数组时,质数输出2、3、5、7、11、13、17和19。然后它说质数总数=9。但是应该是8。
这是我的代码
public class Prime {
public static void main(String[] args) {
int index = 0;
Scanner scan = new Scanner(System. in );
System.out.println("How big would you like the array? ");
int num = scan.nextInt();
int[] array = new int[num];
ArrayList < Integer > primes = new ArrayList < Integer > ();
//System.out.println("How Many threads? ");
//int nThreads = scan.nextInt(); // Create variable 'n' to handle whatever integer the user specifies. nextInt() is used for the scanner to expect and Int.
//Thread[] thread = new Thread[nThreads];
for (int n = 1; n <= array.length; n++) {
boolean prime = true;
for (int j = 2; j < n; j++) {
if (n % j == 0) {
prime = false;
break;
}
}
if (prime) {
primes.add(n);
}
if (prime && n != 1) {
System.out.println(n + "");
}
}
System.out.println("Total Prime numbers = " + primes.size());
System.out.println("Prime Numbers within " + array.length);
}
}
原谅它的草率。 我实际上计划在其中添加多线程,但是我想首先考虑一下。
任何帮助将不胜感激。 谢谢。
您已在素数数组中包含1
,因为您在1
处启动了n
for循环。 由于最后的if
语句,您不打印它,但是它在ArrayList
。
从n = 2
开始您的n
for循环。 结果,您将不需要最终的if
语句,因为n
永远不会为1
。 您可以在将素数添加到ArrayList
的同时打印素数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.