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();
			}
		}
	}
}

在这里插入图片描述

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