所有可能性的用户输入验证

时间:2017-10-21 05:19:04

标签: java user-input

我试图确保用户只输入一个int,并且它的范围是10到20左右 当我第一次输入超出范围的int然后输入一个字符串时,我最终得到一个错误。我不确定如何继续要求用户继续输入,直到数字落在指定范围之间。 任何帮助将不胜感激!

public static void main(String[] args) {

    Scanner scnr = new Scanner(System.in);

    int width = 0;
    int height = 0;

    System.out.println("Welcome to Mine Sweeper!");
    System.out.println("What width of map would you like (10 - 20): ");
    //width = scnr.nextInt()
    while (!scnr.hasNextInt()) {
        System.out.println("Expected a number from 10 to 20");
        scnr.next();
    }
    do {
        width = scnr.nextInt();
        if (width < 10 || width > 20) {
            System.out.println("Expected a number from 10 to 20");
            //width = scnr.nextInt();
        }
    } while (width < 10 || width > 20);
}

3 个答案:

答案 0 :(得分:0)

试试这个:

Vector vec = new Vector(4);

vec.add(4);
vec.add(3);
vec.add(2);
vec.add(1);
vec.add(3.55);

Number[] anArray = new Number[vec.size()];
anArray = (Number[]) vec.toArray(anArray); 

答案 1 :(得分:0)

这应该做你想要的:

while (scnr.hasNext()) {
    if (scnr.hasNextInt()) {
        width = scnr.nextInt();
        if (width >= 10 && width <= 20) {
            break;
        }
    }else{
        scnr.next();
    }
    System.out.println("Expected a number from 10 to 20");
}
System.out.println("width = " + width);

答案 2 :(得分:0)

据我了解,您只想接受介于10和20之间的整数值。如果输入了字符或字符串,则需要打印消息并继续执行。如果是这样,那么这应该接近你想要的。我原本打算使用 try-catch 语句来回答这个问题但是,我注意到你回答了另一个答案并说你想要一种不同于使用 try-catch 的方法。此代码不是100%功能;你将不得不调整一些东西,但它与我想要的非常接近,我认为不使用 try-catch 语句。

public static void main(String args[])
{
    Scanner scanner = new Scanner(System.in);
    int width = 0;
    int height = 0;
    int validInput = 0; //flag for valid input; 0 for false, 1 for true

    System.out.println("Welcome to Mine Sweeper!");
    System.out.println("What width of map would you like (10 - 20): ");

    while (validInput == 0) //while input is invalid (i.e. a character, or a value not in range
    {
        if (scanner.hasNextInt())
        {
            width = scanner.nextInt();
            if (width >= 10 && width <= 20)
            {
                validInput = 1; //if input was valid
            }
            else
            {
                validInput = 0; //if input was invalid
                System.out.println("Expected a number from 10 to 20.");
            }
        }
        else
        {
            System.out.println("You must enter integer values only!");
            validInput = 0; //if input was invalid
        }
        scanner.next();
    }
}