import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BaseInput3 {
/**
* @param args
*/
public static void main(String[] args) {
try {
//先提示一段文字,然后等待用户输入
String str = readUserInput("请你输入数据:");
System.out.println("你输入的是:"+ str);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取用户输入
*
* @param prompt 提示文字
* @return 用户输入
* @throws IOException 如果读取失败
*/
private static String readUserInput(String prompt) throws IOException{
//输出提示文字
System.out.println(prompt);
//用InputStreamReader类 读取数据流(InputStream)中获取的用户输入
//System.in为系统输入流
InputStreamReader is_reader = new InputStreamReader(System.in);
return new BufferedReader(is_reader).readLine();
}
}
改进:对用户输入进行验证
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BaseInput4 {
/**
* @author bigboy
*
*/
public static void main(String[] args) {
try {
String str = readUserInput("请你输入年龄:");
System.out.println("你输入的是" + str);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取用户输入
*
* @param prompt 提示文字
* @return result 用户输入
* @throws IOException 如果读取失败
*/
private static String readUserInput(String prompt)throws IOException{
//先定义用户输入的变量
String result;
do{
//输出提示文字
System.out.println(prompt);
//用InputStreamReader类 读取数据流(InputStream)中获取的用户输入
//System.in为系统输入流
InputStreamReader is_reader = new InputStreamReader(System.in);
//用result变量接收用户输入
result = new BufferedReader(is_reader).readLine();
}while(isInvaild(result));//当用户输入无效时反复提示输入
return result;
}
/**
* 检查用户输入是否无效
*
* @param str 用户输入的内容
* @return 如果用户输入的内容无效则返回true
*/
private static boolean isInvaild(String str) {
//str.matches("//d+") 用来判断字符串是不是全是数字d
return str.equals("")||!str.matches("//d+");
}
}