package io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//一个处理输入数据的类(用正则表达式验证),只能输入整数
class MyInput {
private BufferedReader reader = null;
public MyInput() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String getString(String info) {//得到用户输入的字符串
String temp = null;
System.out.println(info);
try {
temp = this.reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return temp;
}
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);
}
}
Java.io.BufferedReader一个处理输入数据的类
最新推荐文章于 2024-09-20 21:13:20 发布