# 在JAVA程序中有语法错误，用于确定数字是否为质数。

go评论25阅读模式

there is some sort of error in the syntax of the program "to determine whether the number is prime or not" in JAVA

# 问题

int n = sc.nextInt();

boolean isPrime = true;

for (int i = 2; i < n; i = i + 1) {
if (n % i == 0) {
isPrime = false;
break;
}
}

if (isPrime == true)
System.out.println("the number is prime");

else if (isPrime == false)
System.out.println("the number is not prime");

Even if I input the number "4", it shows that the number is prime. Please help to find error in the syntax. I have written below the program I coded :

int n = sc.nextInt();

boolean isPrime = true;

for (int i = 2;  i &lt; n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}

if (isPrime = true)
System.out.println(&quot;the number is prime&quot;);

else if (isPrime = false)
System.out.println(&quot;the number is not prime&quot;);

# 答案1

Boolean比较需要使用双等号==。您目前的方式是，在该检查中将isPrime设置为true。尝试这样做：

if (isPrime == true)

Boolean comparison needs to be done with double equals ==. The way you have it currently, you are setting isPrime to be true in that check. Try this:

if (isPrime == true)

# 答案2

if (isPrime) {
System.out.println("这个数字是素数");
} else {
System.out.println("这个数字不是素数");
}

Your program is not complete. You have written assignment statement instead of boolean expression in if statement. '=' sign is for assignment, As 'isPrime' is a boolean variable you can write isPrime in if expression

if(isPrime)
{
System.out.println(&quot;the number is prime&quot;);

}
else
{
System.out.println(&quot;the number is not prime&quot;);
}

# 答案3

boolean isPrime = true;

for (int i = 2; i < n; i = i + 1) {
if (n % i == 0) {
isPrime = false;
break;
}
}

if (isPrime == true)
System.out.println("这个数字是素数");

else
System.out.println("这个数字不是素数");

boolean isPrime = true;

for (int i = 2; i < n; i = i + 1) {
if (n % i == 0) {
isPrime = false;
break;
}
}

if (isPrime)
System.out.println("这个数字是素数");

else
System.out.println("这个数字不是素数");

Use Equality operator == instead of assignment operator = for checking the value of isPrime.

boolean isPrime = true;

for (int i = 2;  i &lt; n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}

if (isPrime == true)
System.out.println(&quot;the number is prime&quot;);

else
System.out.println(&quot;the number is not prime&quot;);

Also,since if() method's return type is boolean, you can directly check with using ```==````

boolean isPrime = true;

for (int i = 2;  i &lt; n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}

if (isPrime)
System.out.println(&quot;the number is prime&quot;);

else
System.out.println(&quot;the number is not prime&quot;);

</details>

• 本文由 发表于 2020年7月28日 13:20:51
• 转载请务必保留本文链接：https://go.coder-hub.com/63127494.html
• java

go 33

go 41

go 36

go 28