java中,如下代码,如果用户输入的两个都是整数时,就跳出循环,该怎样修改?

import java.io.*;
public class shuru {
public static void main(String[] args) {
System.out.println("请输入两个整数:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
do{
try{
int a=Integer.parseInt(in.readLine());
int b=Integer.parseInt(in.readLine());
}
catch(Exception e){
System.out.println("您输入有误请重新输入:");
}
}while(true);

}
}

你的代码存在太多问题,我个你修改了下,请注意看注释:
import java.io.BufferedReader;
import java.io.IOException; -------导入的包写到具体的包名,不要用*代替。这样系统效率会高点
import java.io.InputStreamReader;

public class shuru {
public static void main(String[] args) {
System.out.println("请输入两个整数:");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

//变量要在循环外定义,减少系统资源 -------问题1
String astr = "";
String bstr = "";
int a = 0;
int b = 0;
do {
try {
astr = in.readLine();
bstr = in.readLine();
} catch (IOException e) {
不要所有的异常都用Exception来代替,不利于定位问题----问题点2
e.printStackTrace();
}

//先排除掉输入是小数的情况,即是否含有"."
if ((astr.indexOf(".")!=-1) || (bstr.indexOf(".") != -1)){
System.out.println("您输入有误请重新输入:");
continue;
}

//再判断是否是数字
try {
//能转换为数字就OK
a = Integer.parseInt(astr);
b = Integer.parseInt(bstr);
System.out.println("第一个数: " + a);
System.out.println("第二个数: " + b);
break;
} catch (NumberFormatException e) {
//出异常就不对
System.out.println("您输入有误请重新输入:");
}
} while (true);
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2011-12-13
double a=Double.parseDouble(in.readLine());
double b=Double.parseDouble(in.readLine());

if( (a==(int)a) && (b==(int)b) ){
break;
}
第2个回答  2011-12-13
在in.readline()函数运行之前,用String类型结构接收,判断这个字符串是不是全部为数字组成,如果是的话,再执行下面的语句,然后break跳出就成了!追问

能不能具体一点,最好写一下程序代码,谢谢!!

相似回答