public int getInt(String info, String err) {//验证输入的字符串 int temp = 0; String string = null; boolean flag = true; while (flag) { string = this.getString(info);//得到用户输入的数据 if (string.matches("^[0-9]+$")) {//正则验证 temp = Integer.parseInt(string); flag = false; } else { System.out.println(err);//提醒用户只能输入整数 } } return temp; } }
public class MyBufferedReader { public static void main(String[] args) throws Exception { int n1 = 11; int n2 = 5; MyInput myInput = new MyInput(); int int1 = myInput.getInt("请输入第一个数字", "只能输入数字"); int int2 = myInput.getInt("请输入第二个数字", "只能输入数字"); System.out.println(int1 + int2); } }