java
1import java.util.Scanner;
2
3public class readInteger {
4
5 public static void main(String[] args) {
6 // play();
7 // playA();
8 // playB();
9 playC();
10 }
11
12 public static void play() {
13 int rounds;
14 Scanner scan = new Scanner(System.in);
15 while (true) {
16 System.out.print("ゲーム回数を入力してください:");
17 try {
18 rounds = scan.nextInt();
19 while (rounds < 0) {
20 System.out.println("エラーです。\n");
21 System.out.print("ゲーム回数を入力してください:");
22 rounds = scan.nextInt();
23 }
24 break;
25 } catch (Exception e) {
26 System.out.println("エラーです。\n");
27 }
28 }
29 System.out.println("回数:" + rounds);
30 }
31
32 public static void playA() {
33 // "a b" と入力すると 2 回 エラーメッセージが出る
34 int rounds;
35 Scanner scan = new Scanner(System.in);
36 while (true) {
37 try {
38 System.out.print("ゲーム回数を入力してください:");
39 rounds = scan.nextInt();
40 break;
41 } catch (Exception e) {
42 System.out.println("エラーです。\n");
43 // 入力バッファのクリア
44 scan.next();
45 }
46 }
47 System.out.println("回数:" + rounds);
48 }
49
50 public static void playB() {
51 // " 1" と入力すると、エラーメッセージが出る
52 int rounds;
53 Scanner scan = new Scanner(System.in);
54 while (true) {
55 try {
56 System.out.print("ゲーム回数を入力してください:");
57 rounds = Integer.parseInt(scan.nextLine());
58 break;
59 } catch (Exception e) {
60 System.out.println("エラーです。\n");
61 }
62 }
63 System.out.println("回数:" + rounds);
64 }
65
66 public static void playC() {
67 // " 1" と入力すると、1 と認識する
68 int rounds;
69 Scanner scan = new Scanner(System.in);
70 while (true) {
71 try {
72 System.out.print("ゲーム回数を入力してください:");
73 rounds = Integer.parseInt(scan.nextLine().trim());
74 break;
75 } catch (Exception e) {
76 System.out.println("エラーです。\n");
77 }
78 }
79 System.out.println("回数:" + rounds);
80 }
81}
play() は質問文にあるコードです。
"a" と入力すると、エラーメッセージ表示が無限ループしてしまいます。
playA() は、無限ループしないように scan.next() 呼び出しを追加しました。また while を1 つに減らしました。
"a b" と入力すると、 2 回 エラーメッセージが表示されます
。
playB() は "a b" と入力しても、1回だけのエラーメッセージとなるようにしたものです。(行単位で入力を処理するようにしました)
" 3" と入力すると、エラーメッセージが表示されます。
playC() は、 " 3" を 3 と認識するようにしたものです。 (先頭の空白を取り除くようにしました)
参考情報
https://ameblo.jp/slont-code/entry-11886344684.html