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