我必须使用for循环获得素数,我拥有一切并运行,但它总是返回“是素数”
示例输出:
1201 IS PRIME.
77 IS NOT PRIME.
1213 IS PRIME.
88 IS NOT PRIME.
1217 IS PRIME.
99 IS NOT PRIME.
121 IS NOT PRIME.
1431 IS NOT PRIME.
1223 IS PRIME.
141 IS NOT PRIME.
234 IS NOT PRIME.
97 IS PRIME.
436 IS NOT PRIME.
47 IS PRIME.
7 IS PRIME.
547 IS PRIME.
2456 IS NOT PRIME.
34 IS NOT PRIME.
代码:
import static java.lang.System.*;
import java.lang.Math;
public class Prime
{
private int j;
private int result = 0;
public Prime()
{
j = 0;
}
public Prime(int num)
{
j = num;
}
public void setPrime(int num)
{
j = num;
}
//boolean isPrime() goes here
public boolean isPrime()
{
boolean prime = true;
for(int i = 2; i<= j/2; i++)
{
if(j % i >= 0)
{
prime = false;
}
prime = true;
}
return prime;
}
public String toString()
{
if( isPrime() == false)
{
return "Number: " + j + " is Not Prime.";
}
else
{
return "Number: " + j + " is Prime. ";
}
}
}
我设置了跑步者,我正在读取文件。问题是java不会通过后面的if语句。
答案 0 :(得分:2)
你的病情错了。
if(j % i >= 0)
总是如此。
将其更改为
if(j % i == 0)
从循环中移除prime = true;
,否则您的方法将始终返回true
。
实际上,您可以删除prime
变量,只需在找到除数后返回false
:
public boolean isPrime()
{
for(int i = 2; i<= j/2; i++)
{
if(j % i == 0)
{
return false;
}
}
return true;
}