oryan5000
oryan5000

Reputation: 91

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

How can I use the scanner hasNext() method to ensure that the user only selects a value between 1 and 20 and then use that value as a String to return in fillSpot variable? The code below is lacking a way to check if the input is between 1 and 20. I am also receiving the error code fillSpot cannot be resolved to a variable on the final return line. Any help would be much appreciated!

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

Upvotes: 0

Views: 144

Answers (2)

falknis
falknis

Reputation: 141

You can also try this and based on your requirement you can return a String or an Integer.

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

Upvotes: 1

I would suggest something like this :

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

}

Let me know if it helps.

Upvotes: 1

Related Questions