回答編集履歴

3

追記

2018/03/09 17:04

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -59,3 +59,59 @@
59
59
  }
60
60
 
61
61
  ```
62
+
63
+
64
+
65
+ このままコンパイルがとおるコード
66
+
67
+ ---
68
+
69
+ ```Java
70
+
71
+ import java.util.Scanner;
72
+
73
+
74
+
75
+ class Main {
76
+
77
+ static int inputNum(String message, Scanner sc) {
78
+
79
+ while(true) {
80
+
81
+ System.out.println(message);
82
+
83
+ try {
84
+
85
+ int ret = Integer.parseInt(sc.nextLine());
86
+
87
+ if(0 < ret && ret <= 10) {
88
+
89
+ return ret;
90
+
91
+ }
92
+
93
+ }
94
+
95
+ catch(NumberFormatException e) {}
96
+
97
+ }
98
+
99
+ }
100
+
101
+
102
+
103
+ public static void main(String[] args) {
104
+
105
+ try(Scanner sc = new Scanner(System.in)) {
106
+
107
+ int num = inputNum("1~10の数を入れてね", sc);
108
+
109
+ System.out.println("入力された数: " + num);
110
+
111
+ }
112
+
113
+ }
114
+
115
+ }
116
+
117
+ ```

2

修正

2018/03/09 17:04

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -3,10 +3,6 @@
3
3
  ```Java
4
4
 
5
5
  static int inputNum(String message, Scanner sc) {
6
-
7
- int ret;
8
-
9
-
10
6
 
11
7
  while(true) {
12
8
 
@@ -14,19 +10,17 @@
14
10
 
15
11
  try {
16
12
 
17
- ret = Integer.parseInt(sc.nextLine());
13
+ int ret = Integer.parseInt(sc.nextLine());
14
+
15
+ if(0 < ret && ret <= 10) {
16
+
17
+ return ret;
18
+
19
+ }
18
20
 
19
21
  }
20
22
 
21
- catch(NumberFormatException e) {
23
+ catch(NumberFormatException e) {}
22
-
23
- continue;
24
-
25
- }
26
-
27
-
28
-
29
- if(0 < ret && ret <= 10) return ret;
30
24
 
31
25
  }
32
26
 

1

再帰

2018/03/09 04:36

投稿

LouiS0616
LouiS0616

スコア35660

test CHANGED
@@ -33,3 +33,35 @@
33
33
  }
34
34
 
35
35
  ```
36
+
37
+
38
+
39
+ 再帰バージョン。
40
+
41
+ ```Java
42
+
43
+ static int inputNumRecursive(String message, Scanner sc) {
44
+
45
+ System.out.println(message);
46
+
47
+ try {
48
+
49
+ int ret = Integer.parseInt(sc.nextLine());
50
+
51
+ if(0 < ret && ret <= 10) {
52
+
53
+ return ret;
54
+
55
+ }
56
+
57
+ }
58
+
59
+ catch(NumberFormatException e) {}
60
+
61
+
62
+
63
+ return inputNumRecursive(message, sc);
64
+
65
+ }
66
+
67
+ ```