* * * * * 重要的鍵盤輸入類InputData!

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

public class InputData {
	private BufferedReader buf = null;

	public InputData() {// 只要輸入數據就要使用此語句
		this.buf = new BufferedReader(new InputStreamReader(System.in));
	}

	public String getString(String info) { // 得到字符串信息
		String temp = null;
		System.out.print(info); // 打印提示信息
		try {
			temp = this.buf.readLine(); // 接收數據
		} catch (IOException e) {
			e.printStackTrace();
		}

		return temp;
	}

	public int getInt(String info, String err) { // 得到一個整數的輸入數據
		int temp = 0;
		String str = null;
		boolean flag = true; // 定義一個標記位
		while (flag) {
			str = this.getString(info); // 接收數據
			if (str.matches("^\\d+$")) { // 判斷是否由數字組成
				temp = Integer.parseInt(str); // 轉型
				flag = false; // 結束循環
			} else {
				System.out.println(err); // 打印錯誤信息
			}
		}
		return temp;
	}

	public float getFloat(String info, String err) { // 得到一個小數的輸入數據
		float temp = 0;
		String str = null;
		boolean flag = true; // 定義一個標記位
		while (flag) {
			str = this.getString(info); // 接收數據
			if (str.matches("^\\d+.?\\d+$")) { // 判斷是否由數字組成
				temp = Float.parseFloat(str); // 轉型
				flag = false; // 結束循環
			} else {
				System.out.println(err); // 打印錯誤信息
			}
		}
		return temp;
	}

	public Date getDate(String info, String err) { // 得到一個日期的輸入數據
		Date temp = null;
		String str = null;
		boolean flag = true; // 定義一個標記位
		while (flag) {
			str = this.getString(info); // 接收數據
			if (str.matches("^\\d{4}-\\d{2}-\\d{2}$")) { // 判斷是否由數字組成
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					temp = sdf.parse(str); // 將字符串變爲Date型數據
				} catch (Exception e) {
				}
				flag = false; // 結束循環
			} else {
				System.out.println(err); // 打印錯誤信息
			}
		}
		return temp;
	}

	public String getPath(String info, String err) { // 得到一個路徑格式的輸入字符串
		String str = "";
		String s = "";
		boolean flag = true; // 定義一個標記位
		while (flag) {
			str = this.getString(info); // 接收數據
			String ts = str.trim();// 馬蛋,這個也不能少,實際讀取的可能比字符長,出現空格造成路徑出錯。
			// 下面的路徑正則要求文件或文件夾只能用字母數字下劃線,可以有擴展名
			if (ts.matches("^[a-zA-Z]:[\\\\\\w+]+.?\\w*$|^[a-zA-Z]:[/\\w+]+.?\\w*$")) {// String中\要用\\\\表示,|的運算優先級最後
				char c[] = ts.toCharArray();
				for (int i = 0; i < c.length; i++) {
					if (String.valueOf(c[i]).equals("\\") || String.valueOf(c[i]).equals("/")) {// 將/換成File.separator纔是正道,以適應各種系統。
						s = s + File.separator;// 在遇到其他系統,對分隔符的判斷還要擴大。
					} else {
						s = s + c[i];
					}
				}
				flag = false; // 結束循環
			} else {
				System.out.println(err); // 打印錯誤信息
			}
		}
		return s;
	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章