Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java How to loop until variable is equal to a specific type (String/int)

Tags:

java

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; 
  }
like image 230
Herten Ferford Avatar asked Feb 20 '26 18:02

Herten Ferford


2 Answers

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();
  • Scanner.next()
  • Scanner.hasNextInt()
  • Validating input using java.util.Scanner
like image 51
calebds Avatar answered Feb 22 '26 08:02

calebds


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);
like image 23
Louis Wasserman Avatar answered Feb 22 '26 07:02

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!