College assignment for testing a positive number (called num) is a Prime Number or not. I must use a Do while loop Ive attempted the code as follows but its failing the test
public class Primes {
public static main void (String args[]){
int num = 1;
int 2 = 0;
boolean flag = false;
do {
if (num%i == 1) {
flag = true;
break:
}
num ++
while (i<=num);
{
if (flag = true);
{
System.out.println (num + "is a prime number ");
}
else
{
System.out.prinln (num + "is not a prime number ");
}
}
}
}
it should be
public static void main(String args[])
not
public static main void (String args[])
int 2 = 0;
you probably mean
int i = 0;
do { ... } while(...);
The format of a do while loop is
do {
something();
} while (condition);
while (condition); {
something();
}
in this case something()
is not in your while loop
if
if (flag = true)
this is assigning flag
to true
. And the condition is always true (since the resulting of the assignment is true).
System.out.prinln
It is System.out.println
. Use an IDE.
public class Primes {
public static void main(String args[]) {
int num = 3;
int i = 2;
boolean flag = false;
do {
if (num % i == 0) {
flag = true;
break;
}
i++;
} while (i < num);
if (!flag) {
System.out.println(num + " is a prime number ");
} else {
System.out.println(num + " is not a prime number ");
}
}
}
I also fixed some logical problem such as
i
instead of num
,while (i < num)
instead of while (i<=num)
, otherwise some (last) i
always equals to num
, making everything not a prime if
logic. Flag is true when you find something that is evenly divisible, meaning the number is not a prime.There are better solutions, but I stick with your format.
You have a couple of different issues:
Firstly, it should be:
public static void main(String[] args){
Second, your variable on line 4 doesn't have name.
Your format for your do while statement is also, not quite right.
Another poster has a good example of a do while loop here: Do-while loop java explanation
Also, go over the rules for where semicolons should be placed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.