Suppose I would like to add a method to Scanner called nextPositiveInt()
which is similar to nextInt()
except that when a negative integer is detected, a custom InputNegativeException
is thrown.
Why would I want to do this when there are solutions that utilise hasNextInt()
? While being a little less concise, it seems a whole lot tidier and more logical given the purpose of exceptions. For example:
Extended Scanner method:
Scanner cli = new Scanner(System.in);
boolean inputValid = false;
do
{
System.out.println("Enter your age:");
try
{
int age = cli.nextPositiveInt();
}
catch(InputNegativeException e)
{
System.out.println("You cannot specify a negative age.");
inputValid = false;
}
catch(InputMismatchException e)
{
System.out.println("Your input must be numeric.");
inputValid = false;
}
} while(!inputValid);
hasNext()
method:
Scanner cli = new Scanner(System.in);
do
{
System.out.println("Please enter a positive number!");
while(!sc.hasNextInt())
{
System.out.println("That's not a number!");
sc.next(); // this is important!
}
int number = sc.nextInt();
} while(number <= 0);
So assuming you aren't already firing up a response telling me why this is a very bad idea (if it is, please do; I imagine there might be some objection regarding putting validation in Scanner) I'm confused about how to go about this. I guess I need to replicate the body of nextInt()
in nextPositiveInt()
with some minor changes? Can you even source the body of nextInt()
anywhere?
I apologise that I have no code to show any effort I've made but I'm not sure where to start.