我有一个控制台应用程序,我需要输入数字,直到输入“x”。 当然,当我输入“x”时,我将得到一个NumberFormatException。
输入“x”时如何退出程序而不会出现异常。
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
String s;
int input;
String name = args[0];
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
System.out.println("Good morning " + name + " Today's date is " + sdf.format(date));
System.out.println("Please enter any number between 0 and 10");
try
{
do
{
s = buf.readLine();
input = Integer.parseInt(s);
while(input <= 0 || input > 10)
{
System.out.println("Make sure about the correct input...between 0 and 10 please");
s = buf.readLine();
input = Integer.parseInt(s);
System.out.println(input);
}
}while(s != "x");
答案 0 :(得分:3)
重新排序循环以检查s
之前x
是否等于Integer.parseInt()
。使用String.equals()
来比较字符串,而不是==
或!=
。
由于这是作业,我不会发布修改后的代码。
编辑:
只是解释使用String.equals()
的原因:
来自 Java语言规范3.0 的 15.21.3参考等式运算符==和!= 部分:
虽然==可用于比较String类型的引用,但这样的相等性测试确定两个操作数是否引用相同的String对象。如果操作数是不同的String对象,则结果为false,即使它们包含相同的字符序列。可以通过方法调用s.equals(t)测试两个字符串s和t的内容是否相等。
答案 1 :(得分:3)
只需添加一行
即可s = buf.readLine();
if ("x".equals(s)) break; // add this line
这并不能保证s
是一个整数,所以你仍然需要捕获像andreas的那样的异常
答案 2 :(得分:2)
将代码包装在try..catch块中。
input=-1;
try{
input = Integer.parseInt(s);
while(input <= 0 || input > 10)
{
System.out.println("Make sure about the correct input...between 0 and 10 please");
s = buf.readLine();
input = Integer.parseInt(s);
System.out.println(input);
}
}catch(Exception ex) { }
....
答案 3 :(得分:2)
将Integer.parseInt
语句包装在try / catch块中:
try {
input = Integer.parseInt(s);
} catch{NumberFormatException nfe) {
System.out.println("Illegal input");
// know you could do one of the following: (uncomment)
// continue; // would continue the while loop
// break; // would exit the while loop
// System.exit(0); // would exit the application
}
答案 4 :(得分:2)
更改为while循环并执行
while (s != "x") {
// your logic
}
或在此行之前检查s!=“x”:
input = Integer.parseInt(s);
答案 5 :(得分:2)
抓住例外:
s = buf.readLine();
if("x".compareToIgnoreCase(s)) {
// im quit
return;
}
答案 6 :(得分:1)
在将字符串转换为int:
之前添加if语句 if(s.equals("x"))
system.exit(1);
else{
input = Integer.parseInt(s);
while(input <= 0 || input > 10)
{
System.out.println("Make sure about the correct input...between 0 and 10 please");
s = buf.readLine();
input = Integer.parseInt(s);
System.out.println(input);
}