使用io流讀取控制檯輸入的信息
避免了繁瑣的
System.out.println("請輸入數字:")
Scanner input = new Scanner(System.in);
int a = input.nextInt();
System.out.println("請輸入字符串:")
String b = input.next();
//...
//很噁心,繁瑣
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* <p>ClassName: InputUtils</p>
* <p>Description: </p>
* @author gangye
* @date 2018年12月24日 下午4:48:20
*/
public class InputUtils {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//接收控制檯輸入的int值
public static int inputInt(String msg) {
//輸出提示信息
System.out.println(msg);
int input = -1;
try {
String line = br.readLine();
input = Integer.valueOf(line);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("輸入的不是數字,請重新輸入!");
//出現異常後,提示用戶繼續操作
return inputInt(msg);
}
return input;
}
//接收控制檯輸入的long值
public static long inputLong(String msg) {
//輸出提示信息
System.out.println(msg);
long input = -1;
try {
String line = br.readLine();
input = Long.valueOf(line);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("輸入的不是數字,請重新輸入!");
//出現異常後,提示用戶繼續操作
return inputLong(msg);
}
return input;
}
//接收控制檯輸入的double值
public static double inputDouble(String msg) {
//輸出提示信息
System.out.println(msg);
double input = -1;
try {
String line = br.readLine();
input = Double.valueOf(line);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("輸入的不是數字,請重新輸入!");
//出現異常後,提示用戶繼續操作
return inputDouble(msg);
}
return input;
}
//接收控制檯輸入的float值
public static float inputFloat(String msg) {
//輸出提示信息
System.out.println(msg);
float input = -1;
try {
String line = br.readLine();
input = Float.valueOf(line);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("輸入的不是數字,請重新輸入!");
//出現異常後,提示用戶繼續操作
return inputFloat(msg);
}
return input;
}
//接收控制檯輸入的String值
public static String inputString(String msg) {
//輸出提示信息
System.out.println(msg);
String input = null;
try {
input = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return input;
}
}