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



我试图确保用户只输入一个 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);
}

这应该可以做你想要的:

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);

试试这个:

    Scanner scnr = new Scanner(System.in);
    int width = 0;
    int height = 0;
    System.out.println("Welcome to Mine Sweeper!");
    while(true)
    {
        System.out.println("What width of map would you like (10 - 20): ");
        try{
            width = scnr.nextInt();
            System.out.println(width);
            if (width < 10 || width > 20)
            {
                System.out.println("Expected a number from 10 to 20");
            }
            else
                break;
        }catch(Exception e)
        {
            System.out.println("Expected a number from 10 to 20");
            scnr.next();
        }
    }
    scnr.close();

据我了解,您只想接受 10 到 20 之间的整数值(包括 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();
    }
}

相关内容

  • 没有找到相关文章

最新更新