반응형
자바 (java) 입력한 숫자의 소수 여부 판단
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
import java.util.InputMismatchException;
import java.util.Scanner;
// is input number prime number
public class PrimeNumber {
public static void main(String[] args) {
execute();
}
public static void execute() {
int num = inputNumber();
System.out.printf("%d%6s \n", num, booleanToString(isPrime(num)));
}
public static int inputNumber() {
try {
Scanner input = new Scanner(System.in);
System.out.print("Input a number: ");
int num = input.nextInt();
input.close();
if (num <= 0) throw new Exception();
return num;
} catch (InputMismatchException ime) {
System.out.println("Input type integer!!");
return inputNumber();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Input integer bigger than 0!!");
return inputNumber();
}
}
public static Boolean isPrime(int num) {
int max = (int) Math.sqrt(num);
boolean isPrime = true;
for (int i = 2; i <= max; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime ? Boolean.TRUE : Boolean.FALSE;
}
public static String booleanToString(boolean b) {
return b ? " is a prime number." : " is not a prime number.";
}
}
|
cs |
try-with-resource 활용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
import java.util.InputMismatchException;
import java.util.Scanner;
// is input number prime number
public class PrimeNumber {
public static void main(String[] args) throws InterruptedException {
execute();
}
public static void execute() throws InterruptedException {
int num = getInputNumber();
System.out.printf("%d%6s \n", num, booleanToString(isPrime(num)));
}
public static int getInputNumber() throws InterruptedException {
int num = 0;
// try-with-resource
try (Scanner input = new Scanner(System.in)) {
try {
System.out.print("Input a number: ");
num = input.nextInt();
if (num <= 1) throw new Exception();
return num;
} catch (InputMismatchException ime) {
System.out.println("Input type integer!!");
return getInputNumber();
} catch (Exception e) {
e.printStackTrace();
Thread.sleep(10); // throws InterruptedException
System.out.println("Input integer bigger than 1!!");
return getInputNumber();
}
}
}
public static Boolean isPrime(int num) {
int max = (int) Math.sqrt(num);
boolean isPrime = true;
for (int i = 2; i <= max; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
return isPrime ? Boolean.TRUE : Boolean.FALSE;
}
public static String booleanToString(boolean b) {
return b ? " is a prime number." : " is not a prime number.";
}
}
|
cs |
반응형
'JAVA 자바 > JAVA 실습_기초' 카테고리의 다른 글
[JAVA #18] 소인수분해 (0) | 2020.05.29 |
---|---|
[JAVA #17] 배열의 합계 및 평균 (0) | 2020.05.25 |
[JAVA #15] 100이하 가장 큰 소수 (0) | 2020.05.17 |
[JAVA #14] 자바 1부터 100까지의 자연수의 합 (0) | 2020.05.02 |
[JAVA #13] 자바 문자열이 포함한 특정 문자의 개수 (2) | 2020.05.02 |