Java如何循环,直到变量等于特定类型(String / int) [英] Java How to loop until variable is equal to a specific type (String/int)
本文介绍了Java如何循环,直到变量等于特定类型(String / int)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好我正在开发一个小型预订程序,我很高兴知道我是否可以使用Loop来运行,直到变量等于特定类型,特别是String或An Integer。
例如我在下面有以下内容,我希望用户始终输入一个数字。
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.?
问候。
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();
- Scanner.next()
- Scanner.hasNextInt()
- 使用java.util验证输入。扫描仪
- Scanner.next()
- Scanner.hasNextInt()
- Validating input using java.util.Scanner
这篇关于Java如何循环,直到变量等于特定类型(String / int)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文