【问题标题】:Java validating inputJava 验证输入
【发布时间】:2018-05-07 21:30:28
【问题描述】:

是否可以在 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();
    }

【问题讨论】:

  • 单步调试您的代码,看看发生了什么

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


【解决方案1】:

您可以尝试使用String 代替int。然后,您可以再次使用Integer.parseInt(x) 继续int,因为它已经在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);
/* .
   .
   .  *\

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-28
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多