jekkiez
jekkiez

Reputation: 19

How can I not allow user input if it is not an int using a scanner?

I am a very new programmer and I just learned about scanner, but I am trying to find a way to make it so when I press the up or down keys, it cycles through the options, putting a > in front to know that it is the option currently selected.

This is the prompt:

What would you like to do:  
Attack   
Inventory  
Stats  
Flee

I would like it to have an arrow in front of the selected one and change the selection with the up and down arrow keys. So for example, as soon as you are prompted it looks like this:

What would you like to do:

What would you like to do:  
> Attack   
Inventory  
Stats  
Flee

And if you pressed the down arrow key twice:

What would you like to do:  
Attack   
Inventory  
> Stats  
Flee

So my current code looks like this:

public class Prompter {

    Scanner input = new Scanner(System.in);
    public int options() throws IOException {
        System.out.printf("What would you like to do:%nAttack %n Inventory %n Stats %n Flee %n");
        while (!input.hasNextInt()) input.next();
        int choice = input.nextInt();
        System.out.printf("Choice: %d", choice);
    return choice;
    }
}

What it does right now is accepts an int input and returns it.

Please do not send me a huge block of code without explaining it because I am a pretty new programmer. Thanks!

Upvotes: 1

Views: 64

Answers (1)

xry
xry

Reputation: 707

As mentioned in the comments before it is not possible to implement such a behaviour easily in the console.

An easy workaround could be to map numbers behind the options. (Attack (1), Inventory (2),..) and extend your code like:

int inputChoice = input.nextInt();
String choice = "";
switch(inputChoice){
      case 1: choice = "Action";
      case 2: choice = "Inventory";
      // add cases
}
System.out.println("Choice: " +choice);
return choice; // or inputChoice if you want to return an int value

It's not the best way to do this but could be enough for your current need.

Upvotes: 1

Related Questions