英文:
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 < 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");
答案1
得分: 0
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
得分: 0
你的程序尚未完成。在if语句中,你写了赋值语句而不是布尔表达式。'='符号用于赋值,由于'isPrime'是一个布尔变量,你可以在if表达式中写'isPrime'。
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("the number is prime");
}
else
{
System.out.println("the number is not prime");
}
答案3
得分: 0
使用相等运算符 ==
来检查 isPrime
的值,而不是赋值运算符 =
。
你的代码应该是:
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("这个数字不是素数");
另外,由于 if()
方法的返回类型是布尔值,你可以直接使用 ==
进行检查:
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
.
Your code should be:
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
System.out.println("the number is not prime");
Also,since if() method's return type is boolean, you can directly check with using ```==````
boolean isPrime = true;
for (int i = 2; i < n; i = i + 1)
{if (n % i == 0) {
isPrime = false;
break;}
}
if (isPrime)
System.out.println("the number is prime");
else
System.out.println("the number is not prime");
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论