题目:
MyInput.java :Contain the methods for reading int,double,float,boolean,short,byte and string values from the keyboard.
首先分析一下题目:创建一个MyInput.java,判断键盘输入的是int,double,float,boolean,short,byte还是string。
整体实现思路如下,我就简单说一下:
首先标准输入流(System.in)返回的是字节流,标准输入流可以获取到键盘输入到控制台的内容,然后我们需要用readLine()读取一行来进行判断。
具体实现思路详:
readLine()是字符缓冲流(BufferedReader)中的方法,而字节流是节点流的一种(节点流包含字节流和字符流),众所周知,字节流和字符流是两种不同的流,我们要想将字节流转换成字符流,就需要用到官方API中提供的转换流(InputStreamReader):将字节输入流转换成字符输入流。
好了,有了字符流,现在需要考虑如何将字符流转换成缓冲流,节点流和缓冲流之间的关系是缓冲流相较于节点流多了个缓冲区,为了提高流传输的效率,而创建缓冲流需要用到 将节点流作为参数 的构造器,所以大功告成,就剩下基本逻辑了,看代码,看代码,直接看代码,小白也能懂,我不相信有人看不懂,都给我卷起来!!!!
public class MyInput {
public static String readString(){
//Read a String from keyboard
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//Declare and initialize the String
String string = "";
//Get the string from the keyboard
try {
string = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Return the String obtained from the keyboard
return string;
}
//Read an int value from the keyboard
public static int readInt(){
return Integer.parseInt(readString());
}
//Read a double value from the keyborad
public static double readDouble(){
return Double.parseDouble(readString());
}
//Read a byte value from the keyboard
public static double readByte(){
return Byte.parseByte(readString());
}
//Read a short value from the keyboard
public static double readShort(){
return Short.parseShort(readString());
}
//Read a long value from the keyboard
public static double readLong(){
return Long.parseLong(readString());
}
//Read a float value from the keyboard
public static double readFloat(){
return Float.parseFloat(readString());
}
}
如果有想学习IO流的全部各种every流,来我个人主页面:保姆级别。Java-IO流专题,由于现在还在努力创作中,所以就不贴链接了。