回答編集履歴
3
追記
answer
CHANGED
@@ -28,4 +28,32 @@
|
|
28
28
|
|
29
29
|
return inputNumRecursive(message, sc);
|
30
30
|
}
|
31
|
+
```
|
32
|
+
|
33
|
+
このままコンパイルがとおるコード
|
34
|
+
---
|
35
|
+
```Java
|
36
|
+
import java.util.Scanner;
|
37
|
+
|
38
|
+
class Main {
|
39
|
+
static int inputNum(String message, Scanner sc) {
|
40
|
+
while(true) {
|
41
|
+
System.out.println(message);
|
42
|
+
try {
|
43
|
+
int ret = Integer.parseInt(sc.nextLine());
|
44
|
+
if(0 < ret && ret <= 10) {
|
45
|
+
return ret;
|
46
|
+
}
|
47
|
+
}
|
48
|
+
catch(NumberFormatException e) {}
|
49
|
+
}
|
50
|
+
}
|
51
|
+
|
52
|
+
public static void main(String[] args) {
|
53
|
+
try(Scanner sc = new Scanner(System.in)) {
|
54
|
+
int num = inputNum("1~10の数を入れてね", sc);
|
55
|
+
System.out.println("入力された数: " + num);
|
56
|
+
}
|
57
|
+
}
|
58
|
+
}
|
31
59
|
```
|
2
修正
answer
CHANGED
@@ -1,18 +1,15 @@
|
|
1
1
|
適当に静的メソッドを置いておくと便利かと。
|
2
2
|
```Java
|
3
3
|
static int inputNum(String message, Scanner sc) {
|
4
|
-
int ret;
|
5
|
-
|
6
4
|
while(true) {
|
7
5
|
System.out.println(message);
|
8
6
|
try {
|
9
|
-
ret = Integer.parseInt(sc.nextLine());
|
7
|
+
int ret = Integer.parseInt(sc.nextLine());
|
8
|
+
if(0 < ret && ret <= 10) {
|
9
|
+
return ret;
|
10
|
+
}
|
10
11
|
}
|
11
|
-
catch(NumberFormatException e) {
|
12
|
+
catch(NumberFormatException e) {}
|
12
|
-
continue;
|
13
|
-
}
|
14
|
-
|
15
|
-
if(0 < ret && ret <= 10) return ret;
|
16
13
|
}
|
17
14
|
}
|
18
15
|
```
|
1
再帰
answer
CHANGED
@@ -15,4 +15,20 @@
|
|
15
15
|
if(0 < ret && ret <= 10) return ret;
|
16
16
|
}
|
17
17
|
}
|
18
|
+
```
|
19
|
+
|
20
|
+
再帰バージョン。
|
21
|
+
```Java
|
22
|
+
static int inputNumRecursive(String message, Scanner sc) {
|
23
|
+
System.out.println(message);
|
24
|
+
try {
|
25
|
+
int ret = Integer.parseInt(sc.nextLine());
|
26
|
+
if(0 < ret && ret <= 10) {
|
27
|
+
return ret;
|
28
|
+
}
|
29
|
+
}
|
30
|
+
catch(NumberFormatException e) {}
|
31
|
+
|
32
|
+
return inputNumRecursive(message, sc);
|
33
|
+
}
|
18
34
|
```
|