如何验证用户输入是否在特定范围内?

huangapple 未分类评论42阅读模式
英文:

How to validate the user input is in a certain range?

问题

我编写了一个程序询问用户输入介于1到6之间的数字字符串然后返回获得该字符串所需的投掷次数我想要验证输入以防止用户输入大于6或小于1的数字但我似乎无法弄清楚如何实现

int SIDES = 6;
String userString = "null";
String answer = "null";
int length = 0;
do {
    do {
        System.out.print("请输入一个包含6个数字的字符串,用于投掷:");
        userString = keyboard.next();
        while (length != SIDES) {
            System.out.println("请输入一个有效的数字字符串:");
            userString = keyboard.next();
        }
        length = userString.length();
    } while (length != SIDES); // 我想在这行添加验证
    dieRoll(userString);
}
英文:

I wrote a program that asks the person for strings of numbers between 1-6 and returns the number of rolls it took to get the string. I want to validate the input so that the person doesn't enter a number bigger than 6 or smaller than 1 and I can't seem to figure out how to do that.

int SIDES = 6;
String userString = "null";
String answer = "null";
int length = 0;
do {
    do {
        System.out.print("please enter a string of 6 numbers you want to be rolled");
        userString = keyboard.next();
    while (length != SIDES) {
        System.out.println("please enter a valid string number");
        userString = keyboard.next();
    } 
        length = userString.length();
} while ( length != SIDES); // I want to add the validation to this line
dieRoll(userString);

答案1

得分: 0

while (length != SIDES) {
    userString = keyboard.next();
    try {
        int userStringNumber = Integer.parseInt(userString);
        if (userStringNumber < 1 || userStringNumber > 6)
            throw new IllegalArgumentException();
    } catch (NumberFormatException e) {
        System.out.println("Please provide a number");
    }
    catch (IllegalArgumentException ex){
        System.out.println("Number should be between 1 and 6");
    }
}
英文:
while (length != SIDES) {
    userString = keyboard.next();
    try {
        int userStringNumber = Integer.parseInt(userString);
        if(userStringNumber&lt;1||userStringNumber&gt;6)
            throw new IllegalArgumentException();
    } catch (NumberFormatException e) {
        System.out.println(&quot;Please provide a number&quot;);
    }
    catch (IllegalArgumentException ex){
        System.out.println(&quot;Number should be between 1 and 6&quot;);
    }

}

huangapple
  • 本文由 发表于 2020年4月5日 03:45:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/61033850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定