2

ユーザーからの入力を検証しようとしています。ユーザーは Y 座標に (AJ) の間の文字を入力し、x 座標には (1-9) の間の数字を入力します。y 座標は検証できますが、x 座標の検証に問題があります。ユーザーが1から9までの数字以外の何かを入力すると、ユーザーに有効な入力を求め続けます。

    do {
        // inner loop checks and validates user input
        do {

            System.out.println("Enter X Co-Ord (A-J), or Q to QUIT");
            letter = input.next().toUpperCase(); // upper case this for
                                                    // comparison
            if (letter.equals("Q"))
                break; // if user enters Q then quit

            String temp = "ABCDEFGHIJ";

            while (temp.indexOf(letter) == -1) {
                validString = false;
                System.out.println("Please enter a valid input");
                letter = input.next().toUpperCase();
                col = temp.indexOf(letter);

            }

            if (temp.indexOf(letter) != -1) {
                validString = true;
                col = temp.indexOf(letter);

            }
            try {

                System.out.println("Enter Y Co-Ord (0-9)");
                row = input.nextInt();


            } catch (InputMismatchException exception) {
                validInt = false;
                System.out.println("Please enter a number between 1 -9");
            }

            catch (Exception exception) {
                exception.printStackTrace();
            }

            valuesOK = false; // only set valuesOK when the two others are
                                // true
            if (validString && validInt) {
                valuesOK = true;
            }
        } while (!valuesOK); // end inner Do loop

出力は次のとおりです。

X Co-Ord (AJ) または Q を入力して終了します

d

Y 座標を入力してください (0-9)

時間

1 ~ 9 の数字を入力してください

X Co-Ord (AJ) または Q を入力して終了します

Y 座標を入力してください (0-9)

4

2 に答える 2

1

nextInt()手紙を読むときと同じように、 while ループを配置するだけです。

  System.out.println("Enter Y Co-Ord (0-9)");
  row = -1
  while (row < 0) {
    try {
      row = input.nextInt();
      validInt = true;
    } catch (InputMismatchException exception) {
      System.out.println("Please enter a number between 1 -9");
      row = -1;
      validInt = false;
    }
  }
于 2013-01-18T17:04:45.067 に答える
0

人間の目は簡単に行をスキップできるため、検証を要件でより意味のあるものにしたいだけですnextInt()

String value = "";
System.out.println("Enter Y Co-Ord (1-9)");

while (!(value = input.next()).matches("[1-9]+")) {
    System.out.print("Wrong input. Insert again: ");
}

System.out.println(value);

もちろん、正しい値を取得したら、それを再度整数に解析できます (安全に!!!)

于 2013-01-19T06:56:57.170 に答える