java自定義Scanner類似功能類

讀取鍵盤輸入

package com.zjx.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


/**
 * 面試題
 * 讀取鍵盤各個數據類型
 *
 */
public class TestFaceIo {
	public static void main(String[] args) {
		System.out.print("請輸入姓名: ");
		String name = MyInput.readString();
		System.out.print("請輸入年齡: ");
		int age = MyInput.readInt();
		System.out.print("請輸入體重:");
		double weight = MyInput.readDouble();
		System.out.print("請輸入性別:");
		char sex = MyInput.readChar();
		System.out.println(name + "\t" + age + "\t" + weight + "\t" + sex);
		MyInput.close();
	}
}
class MyInput{
	static BufferedReader reader = null;
	/**
	 * 讀取整數
	 * @return
	 */
	public static int readInt(){
		int num = Integer.parseInt(readString());
		return num;
	}
	
	/**
	 * 讀取浮點數
	 * @return
	 */
	public static double readDouble(){
		double num = Double.parseDouble(readString());
		return num;
	}
	
	/**
	 * 讀取char單個字符
	 * @return
	 */
	public static char readChar(){
		char ch = readString().charAt(0);
		return ch;
	}
	
	/**
	 * 讀取字符串
	 * @return
	 */
	public static String readString(){
		try {
			reader = new BufferedReader(new InputStreamReader(System.in));
			String line = reader.readLine();
			return line;
		} catch (Exception e) {
			//編譯異常--》運行異常
			throw new RuntimeException(e);
		} 
	}
	
	/**
	 * 關閉
	 */
	public static void close(){
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

在這裏插入圖片描述

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