使用 hasNext() Scanner 方法只允许一组 X 输入

Using hasNext() Scanner method to only allow a set of X inputs

我如何使用扫描器的 hasNext() 方法来确保用户只选择 1 到 20 之间的值,然后将该值用作 fillSpot 变量中的 return 的字符串?下面的代码缺少检查输入是否在 1 到 20 之间的方法。我还在最后的 return 行收到错误代码 fillSpot cannot be resolved to a variable。任何帮助将非常感激!

public String giveInput() {

    Scanner in = new Scanner(System.in);  
int space;


do {
        System.out.println("Enter numerical value between 1 and 20");  
        while (in.hasNext()) {
            String fillSpot = in.nextLine();  
            System.out.printf("\"%s\" is not a valid input.\n", fillSpot);
        }
        space = in.nextInt();
    } while (space < 1 || space < 20);

    return fillSpot;
}

我建议这样:

public String giveInput() {
        Scanner in = new Scanner(System.in);  
        System.out.println("Enter numerical value between 1 and 20");  
        int input=in.nextInt();
        if(input<1 || input>20) {
            System.out.println(input + " is not a valid input.");
        }else {
            // do your work
            System.out.println("Valid Input");
        }
return Integer.toString(input);

}

如果有帮助请告诉我。

您也可以试试这个,根据您的要求,您可以 return 字符串或整数。

public static String giveInput() {

    Scanner in = new Scanner(System.in);
    String inputString;
    int inputNumber = 0;

    do {
        System.out.println("Enter numerical value between 1 and 20");
        inputString = in.nextLine();
        try {
            inputNumber = Integer.parseInt(inputString);
        } catch (NumberFormatException e) {
            System.err.println("Please enter a number");
        }

    } while (inputNumber < 1 || inputNumber > 20);

    return inputString;
}