java - How can I not allow user input if it is not an int using a scanner? -
i new programmer , learned scanner, trying find way make when press or down keys, cycles through options, putting > in front know option selected.
this prompt:
what do: attack inventory stats flee
i have arrow in front of selected 1 , change selection , down arrow keys. example, prompted looks this:
what do:
what do: > attack inventory stats flee
and if pressed down arrow key twice:
what do: attack inventory > stats flee
so current code looks this:
public class prompter { scanner input = new scanner(system.in); public int options() throws ioexception { system.out.printf("what 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 right accepts int input , returns it.
please not send me huge block of code without explaining because pretty new programmer. thanks!
as mentioned in comments before not possible implement such behaviour in console.
an easy workaround map numbers behind options. (attack (1), inventory (2),..) , extend 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 want return int value
it's not best way enough current need.
Comments
Post a Comment