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()) { //
System.out.println("Please enter a number!");
sc.next(); //
}
return sc.nextInt();