Java验证输入

时间:2018-05-07 21:30:29

标签: java loops validation while-loop java.util.scanner

是否可以在Java中检查某个输入是否在某个范围之间还是整数? 我写了以下代码:

public void getBetAmountFromUser() {
    //Get Amount of Bet
    int x = 0;

    System.out.println("Your current pot is: " + potAmount);
    System.out.println("Enter your bet amount: ");
    x = input.nextInt();
    //Error message if bet is larger than pot and less than 0
    while (x>potAmount || x<0 || !(input.hasNextInt())){
        System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
        x = input.nextInt();
    }
    //Bet should be less than or equal to pot if 0 user quit
    if (x > 0 && x <= potAmount) {
        betAmount = x;
        potAmount = potAmount - betAmount;
    } else if (x == 0) {
        System.out.println("You end the game with pot " + potAmount);
        System.exit(0);
    } 

}

以下循环无法验证整数

while (x>potAmount || x<0 || !(input.hasNextInt())){
        System.out.println("Error - cannot bet less than 0 or more than " + potAmount + "..Enter your bet amount: ");
        x = input.nextInt();
    }

1 个答案:

答案 0 :(得分:0)

您可以尝试使用String代替int。然后,您可以使用int再次继续Integer.parseInt(x),因为在do-while之后它已被验证为有效整数

String x;
String regex = "[0-9]+";  // to check the string only is made up of digits

int potAmount = 10;
Scanner input = new Scanner(System.in);

do {
    System.out.println("Please input an integer");
    x = input.next();
} while (!x.matches(regex) || Integer.parseInt(x) > potAmount || Integer.parseInt(x) < 0);

int validBet = Integer.parseInt(x);
/* .
   .
   .  *\