简体   繁体   中英

Prime Number test beginner Java

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 ");
}
}
}
}

1. Main function signature

it should be

public static void main(String args[])

not

public static main void (String args[])

2. you cannot start a variable name with a number

int 2 = 0;

you probably mean

int i = 0;

3. do { ... } while(...);

The format of a do while loop is

do {
  something();
} while (condition);

4. Semicolon means end of statement

while (condition); {
  something();
}

in this case something() is not in your while loop

5. Watch out for assignment in if

if (flag = true)

this is assigning flag to true . And the condition is always true (since the resulting of the assignment is true).

6. Not System.out.prinln

It is System.out.println . Use an IDE.

Final solution

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

  1. you should probably increment i instead of num ,
  2. while (i < num) instead of while (i<=num) , otherwise some (last) i always equals to num , making everything not a prime
  3. a number is not a prime when flag is true. you should probably invert the 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM