java:BufferedReader接受输入进来的2个数字,并将它们相加
//接受输入进来的2个数字,并将它们相加
BufferedReader buf = null;
buf = new BufferedReader( new InputStreamReader(System.in) );
String str = null;
boolean flag = true;
int i = 0;
int j = 0;
System.out.println("请输入第一个数字:");
while(flag)
{
try {
str = buf.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if( str.matches("\\d+") )
{
i = Integer.parseInt(str);
flag = false;
}else{
System.out.println("请输入第一个数字:");
}
}
flag = true;
System.out.println("请输入第二数字:");
while(flag)
{
try {
str = buf.readLine();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
if( str.matches("\\d+") )
{
j = Integer.parseInt(str);
flag = false;
}else{
System.out.println("请输入第二个数字:");
}
}
System.out.println(i + "+" + j + "=" + (i + j));
}
public Date getDate(String str)
{
Date temp = null;
boolean flag = true;
while(flag)
{
if( str.matches("\\d{4}-\\d{2}-\\d{2}") )
{
try {
temp = new SimpleDateFormat("yyyy-mm-dd").parse(str);
} catch (ParseException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
flag = false;
}else{
System.out.println("您输入的日期有误");
}
}
return temp;
}