范围和输入类型验证

时间:2016-05-26 12:36:43

标签: java validation input while-loop

我有问题。该代码应该采用2位整数,其中数字是不同的。如果它不是整数,则代码会告诉您并要求重新输入。如果它是整数但不符合条件,它将告诉您,然后提示重新输入。一切都有效,除非你输入0来结束循环/程序。我被困在这2天了。有什么建议吗?

    int num = 1;
    while (num != 0) {
        System.out.print("Enter a 2-digit number. The digits should be different. Zero to stop: ");
        while (!in.hasNextInt()) {
            System.out.print("Not an integer, try again: ");
            in.next();
        }
        num = in.nextInt();
        while (num < 10 || num > 99) {
            System.out.println("NOT good for your game!");
            System.out.print("Enter a 2-digit number. The digits should be different. Zero to stop: ");
            while (!in.hasNextInt()) {
                System.out.print("Not an integer, try again: ");
                in.next();
            }
            num = in.nextInt();
        }
        if (equalDigs(num) == false)
            System.out.println("NOT good for you game!");
        else
            System.out.println("Good for your game! Play!");

    }

}
public static boolean equalDigs(int n) {
    int d1 = n / 10;
    int d2 = n % 10;

    if (d1 == d2)
        return false;
    else 
        return true;
}

2 个答案:

答案 0 :(得分:0)

您的问题来自重复检查。您可以使用as.Date()语句而不是do-while语句来减少检查次数:

while

答案 1 :(得分:0)

重构代码的一种方法是从命令行读取String而不是读取数字,然后验证该输入以确保它符合以下条件:

  • 输入长度为两个字符
  • 两个字符都是数字
  • 第一个和第二个数字是唯一的

我创建了一个名为validate()的方法,它可以解决这个问题。这使得main()方法只关注轮询用户输入,只要验证失败。

public static boolean validate(String input) {
    // check that input length is two characters
    if (input.length() != 2) {
        return false;
    }
    // check that a two digit number was entered
    if (Character.getNumericValue(input.charAt(0)) < 0 || Character.getNumericValue(input.charAt(0)) > 9 ||
        Character.getNumericValue(input.charAt(0)) < 0 || Character.getNumericValue(input.charAt(0)) > 9) {
        return false;
    }
    // check that first and second numbers are unique
    if (input.charAt(0) == input.charAt(1)) {
        return false;
    }

    return true;
}

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);
    String input;
    do {
        System.out.println("Enter a 2-digit number. The digits should be different. Zero to stop: ");
        input = reader.next();
        if (!validate(input)) {
            System.out.println("NOT good for your game!");
        }
        else {
            break;
        }
    } while(true);

    System.out.println("Good for your game! Play!");
    // you can also use the value of 'input' here if needed
}