[英]Output amount of primes in array
I'm kind of a newbie at Java, and not very good at it. 我是Java的新手,但不是很好。 It's a trial and error process for me. 对我来说,这是一个反复试验的过程。
I'm working on a Java program to output the amount of primes in an array. 我正在研究一个Java程序来输出数组中的素数。 I can get it to output the primes, but I want to also output the quantity of primes. 我可以输出素数,但也要输出素数。 I tried to add each prime to an array list titled "primes" then return "primes.size()" at the end of my program. 我试图将每个素数添加到标题为“素数”的数组列表中,然后在程序末尾返回“ primes.size()”。 It doesn't work as intended. 它没有按预期工作。 The count is actually off. 计数实际上是关闭的。 When I create an array of 5 numbers, it outputs 3 primes, 2, 3, and 5. But then it says I have 4 primes. 当我创建一个由5个数字组成的数组时,它输出3个质数,2、3和5。但是然后它说我有4个质数。 I think it might be counting 1 as a prime. 我认为可能将1算作素数。 Because when I create an array of 20, the prime numbers output 2,3,5,7,11,13,17 and 19. Then it says the total prime numbers = 9. It should be 8 though. 因为当我创建一个由20组成的数组时,质数输出2、3、5、7、11、13、17和19。然后它说质数总数=9。但是应该是8。
Here's my code 这是我的代码
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);
}
}
Forgive the sloppiness of it. 原谅它的草率。 I actually plan on adding multithreading to it, but I wanted to get this down first. 我实际上计划在其中添加多线程,但是我想首先考虑一下。
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。
You have included 1
in your array of primes, because you started the n
for loop at 1
. 您已在素数数组中包含1
,因为您在1
处启动了n
for循环。 You don't print it because of the final if
statement, but it's there in the ArrayList
. 由于最后的if
语句,您不打印它,但是它在ArrayList
。
Start your n
for loop with n = 2
. 从n = 2
开始您的n
for循环。 As a consequence, you won't need the final if
statement, because n
won't be 1
ever. 结果,您将不需要最终的if
语句,因为n
永远不会为1
。 You could print the prime at the same time as you add it to the ArrayList
. 您可以在将素数添加到ArrayList
的同时打印素数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.