Hi I'm currently developing a small booking program, I'm curios to know if i can use a Loop to run until a variable is equal to a specific type, notably a String or An Integer. For example i have the following below, and I want the user to always enter a number.
If not, am i right in presuming i should just develop a try/catch etc.?
Regards.
public int SetHouseNo(){
System.out.println();
System.out.print("Please enter your house number: ");
HouseNo=in.nextInt();
return HouseNo;
}
How to validate that the user entered an integer, without throwing or catching an exception:
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) { // <-- 'peeks' at, doesn't remove, the next token
System.out.println("Please enter a number!");
sc.next(); // <-- skips over an invalid token
}
return sc.nextInt();
Try/catch is overkill. This is a job for do/while.
int house;
do {
house = in.nextInt();
while (house isn't right for whatever reason);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With