Java如何循环,直到变量等于特定类型(String / int)
嗨我正在开发一个小型预订程序,我很高兴知道我是否可以使用Loop来运行,直到变量等于特定类型,特别是String或An Integer。 例如,我在下面有以下内容,我希望用户始终输入一个数字。
如果没有,我是否正确地假设我应该开发一个try / catch等?
问候。
public int SetHouseNo(){ System.out.println(); System.out.print("Please enter your house number: "); HouseNo=in.nextInt(); return HouseNo; }
如何validation用户输入的整数,而不抛出或捕获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()
- 使用java.util.Scannervalidation输入
尝试/捕获是过度的。 这是do / while的工作。
int house; do { house = in.nextInt(); while (house isn't right for whatever reason);
使用这个简单的循环:
public static int askForInteger(Scanner in, String msg) { while (true) { System.out.print(msg + " "); String input = in.next(); if (input.matches("\\-?\d")) return Integer.parseInt(input); System.out.println("Sorry, you didn't enter a valid number."); } }
如果您只想允许数字,则需要从阅读器中捕获InputMismatchException
。 您可以使用布尔值来指示您是否找到了合适的数字或使用自动装箱/取消装箱,并在找不到合适的值时使用null
值:
Integer houseNumber = null; do { try { System.out.print("Please enter your house number:"); houseNumber = in.nextInt(); } catch (InputMismatchException e) { houseNumber = null; // Not actually necessary, but perhaps clearer } } while (houseNumber == null);
将6更改为“特定”变量(假设HouseNo是一个公共变量,并在输入方法之前初始化为不同于6的值。):
public int SetHouseNo() { System.out.println(); while(HouseNo != 6) { System.out.print("Please enter your house number: "); try { HouseNo=in.nextInt(); } catch(Exception e) { } } return HouseNo; }
有些人不同意这一点,但这就是我要做的事情:
public int SetHouseNo(){ System.out.println(); System.out.print("Please enter your house number: "); try { HouseNo=in.nextInt(); } catch(NumberFormatException nfe) { System.out.println("Please enter a number..."); } return HouseNo; }
然后不知何故,可能在你调用方法的地方,做一个while循环或其他东西,所以它一直询问,直到你输入一个数字。 如果你想,当然…