回答編集履歴

3

InputMismatchExceptionはは

2018/02/07 18:33

投稿

umyu
umyu

スコア5846

test CHANGED
@@ -6,15 +6,13 @@
6
6
 
7
7
  ```Java
8
8
 
9
- import java.util.InputMismatchException;
10
-
11
9
  import java.util.Scanner;
12
10
 
13
11
  import java.util.Set;
14
12
 
15
- import java.util.Arrays;
13
+ import java.util.stream.Collectors;
16
14
 
17
- import java.util.HashSet;
15
+ import java.util.stream.Stream;
18
16
 
19
17
 
20
18
 
@@ -26,67 +24,47 @@
26
24
 
27
25
  // 重複を許可しないなら、配列よりSetを使用するのがベター!
28
26
 
29
- Set<String> exit = Stream.of("exit", "quit").collect(Collectors.toSet());
27
+ Set<String> exit = Stream.of("exit", "quit").collect(Collectors.toSet());
30
-
31
- // もしくはStreamが分かりづらいなら以下のHashSetを使ったコード。
32
-
33
- //Set<String> exit = new HashSet<>(Arrays.asList("exit", "quit"));
34
-
35
-
36
28
 
37
29
  // try~with~Resources文を使う!
38
30
 
39
31
  try (Scanner sc = new Scanner(System.in)) {
40
32
 
41
- try {
33
+ while (true) {
42
34
 
43
- while (true) {
35
+ String input = sc.nextLine();
44
36
 
45
- String input = sc.nextLine();
37
+ // 終了条件は最初に判定する。
46
38
 
47
- // 終了条件は最初に判定する。
39
+ if (exit.contains(input)) {
48
40
 
49
- if (exit.contains(input)) {
41
+ System.out.println(input + "が入力されたので処理を終了します");
50
42
 
51
- System.out.println(input + "が入力されたので処理を終了します");
52
-
53
- break;
43
+ break;
54
-
55
- }
56
-
57
- // 数字に変換。NumberFormatExceptionのチェックもできればすること!
58
-
59
- int n = Integer.valueOf(input);
60
-
61
- if (n < 71) {
62
-
63
- System.out.println(n + "番目のフィボナッチ数は:" + Cst2.fbnt(n));
64
-
65
- System.out.println(n + "番目までのフィボナッチ数列は:" + Cst2.fbn(n));
66
-
67
- } else {
68
-
69
- System.out.println("範囲外です");
70
-
71
- }
72
44
 
73
45
  }
74
46
 
75
- } catch (InputMismatchException misma) {
47
+ // 数字に変換。NumberFormatExceptionのチェックもできればすること!
76
48
 
77
- // System.outではなく System.errへ
49
+ int n = Integer.valueOf(input);
78
50
 
51
+ if (n < 71) {
52
+
53
+ System.out.println(n + "番目のフィボナッチ数は:" + Cst2.fbnt(n));
54
+
55
+ System.out.println(n + "番目までのフィボナッチ数列は:" + Cst2.fbn(n));
56
+
57
+ } else {
58
+
79
- System.err.println(misma);
59
+ System.out.println("範囲外です");
60
+
61
+ }
80
62
 
81
63
  }
82
64
 
83
65
  }
84
66
 
85
-
86
-
87
67
  }
88
-
89
-
90
68
 
91
69
  }
92
70
 

2

Stream.ofに変更

2018/02/07 18:32

投稿

umyu
umyu

スコア5846

test CHANGED
@@ -26,7 +26,13 @@
26
26
 
27
27
  // 重複を許可しないなら、配列よりSetを使用するのがベター!
28
28
 
29
+ Set<String> exit = Stream.of("exit", "quit").collect(Collectors.toSet());
30
+
31
+ // もしくはStreamが分かりづらいなら以下のHashSetを使ったコード。
32
+
29
- Set<String> exit = new HashSet<>(Arrays.asList("exit", "quit"));
33
+ //Set<String> exit = new HashSet<>(Arrays.asList("exit", "quit"));
34
+
35
+
30
36
 
31
37
  // try~with~Resources文を使う!
32
38
 

1

補足!

2018/02/07 17:43

投稿

umyu
umyu

スコア5846

test CHANGED
@@ -1,3 +1,9 @@
1
+ 質問文にはコンパイルエラーが発生しない最小限のソースコードを記載してくださいな。
2
+
3
+ Cst2.fbntとCst2.fbnが質問文のコードに存在しませんでした。
4
+
5
+
6
+
1
7
  ```Java
2
8
 
3
9
  import java.util.InputMismatchException;