I've been taking Java lectures in earnest since yesterday, and I learned about do-while statements. I decided to write a primality test program, so this is a memorandum.

`Sosu.java`

```
package sample;
import java.util.Scanner;
public class Sosu {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
boolean b = true;
while (true) {
System.out.println("Primality test");
System.out.print("Please enter an integer greater than or equal to 2.");
num = sc.nextInt();
if (num < 2) {
System.out.println("An integer less than 2.");
} else {
break;
}
}
if (num == 2) {
System.out.println(num + "Is a prime number.");
} else {
for (int i = 2; i < num; i++) {
if (num % i == 0) {
System.out.println(num + "Is not a prime number.");
b = false;
break;
}
}
if (b) {
System.out.println(num + "Is a prime number.");
}
}
}
}
```

- Play the while statement whose input content is less than 2 and have it re-entered.
- Escape the while statement with break, and judge if the input is 2 or more with the if statement.
- When the input is 2, it is a prime number.
- If the input is greater than 2, divide it by a number greater than or equal to 2 and less than num, and if it is divisible somewhere, it is not a prime number.
- Those that are not divisible are prime numbers. The final judgment is made by boolean.

To be honest, there seems to be a better way, so if I come up with something I've learned in the future, I'll correct it. Also, I would be grateful if you could give me any advice, such as how to do this here in its current form.

Recommended Posts