I currently have a simple function (posted below) which asks the user a question and expects to have an integer answer.
Is there a way to make java restrict the characters that can be entered into the console i.e. only allow numbers to be entered.
I know there are simple ways to do this in other programming languages but How should I go about doing this in java and implementing it into my function?
static int questionAskInt(String question)
{
Scanner scan = new Scanner (System.in);
System.out.print (question+"\n");
System.out.print ("Answer: ");
return scan.nextInt();
}
Using
Scanner.hasNextInt, and while loop, you can restrict the user to give input, until it passes anintegervalue.or, you can also give a certain number of chances (so that it does not go into
infinite loop, by using a count variable: –