Java整数输入验证

时间:2013-01-18 17:00:05

标签: java validation

我正在尝试验证来自用户的输入。用户在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(A-J)或Q to QUIT

d

输入Y Co-Ord(0-9)

ħ

请输入1到9之间的数字

输入X Co-Ord(A-J)或Q to QUIT

输入Y Co-Ord(0-9)

2 个答案:

答案 0 :(得分:1)

你只需要在阅读这封信的同时在nextInt()周围放一个循环:

  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;
    }
  }

答案 1 :(得分: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);

当然,当你得到正确的值时,你可以再次将它解析为整数(安全!!!)