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)

H

请输入一个介于 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 回答