第一种方法,使用正则表达式
Scanner sc = new Scanner(System.in);
String s = sc.next();String s2 = sc.next();
if((s != null && s.matches("^[0-9]+$"))&&(s2 != null && s2.matches("^[0-9]+$"))){
System.out.println("s+s2= "+(Integer.parseInt(s)+Integer.parseInt(s2)));
}else{
System.out.println("输入格式错误");
}
第二种方法 使用try/catch语句
Scanner sc = new Scanner(System.in);
int a;
int b;
try {
a = sc.nextInt();
b = sc.nextInt();
System.out.println("a+b = " + (a + b));
} catch (Exception e) {
System.out.println("输入格式错误!");
}