//待完善
在老师给的Homework1 example里这位同学写的输入流如下
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
BufferedInputStream;
BufferedReader;
readLine() [1]
读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行
FileInputStream;
IOException;
InputStreamReader;
public class PlaylistOperations {
private static BufferedReader input;
public static void main(String[] args){
input = new BufferedReader(new InputStreamReader(System.in));
}
public static String read(){
try {
return input.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
1)input = new BufferedReader(new InputStreamReader(System.in));
“System.in 接受从控制台输入的字节new InputStreamReader(System.in);构造一个InputStreamReader对象
这个对象是字节流通向字符流的桥梁:它使用指定的 charset 读取字节并将其解码为字符。
new BufferedReader(new InputStreamReader(System.in));
构造一个字符流的缓存,里面存放在控制台输入的字节转换后成的字符。
str=buf.readLine();从这个缓存中读取一行的内容
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));整个这句话拆开来写为:
、************************************
InputStream in = System.in ;
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);”[2]
2) return input.readLine();
readLine()
读取一个文本行。通过下列字符之一即可认为某行已终止:换行 ('\n')、回车 ('\r') 或回车后直接跟着换行
返回:
包含该行内容的字符串,不包含任何行终止符,如果已到达流末尾,则返回 null
public static void removeSong(Playlist p){
System.out.println("Enter the position:");
String position = read();
if(position.equals("") || safeParse(position) == -1){
System.out.println("Invalid Input: "
+(position.equals("")?"No Input detected":"Input was not an Integer"));
return;
}
try{
p.removeSong(Integer.parseInt(position));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
return;
}
System.out.println("Song removed at position "+position);
}
1) if(position.equals("") || safeParse(position) == -1)
public static int safeParse(String input){
try{
return new Integer(input).intValue();
} catch (NumberFormatException e){
return -1;
}
}
这段代码的作用是检测输入是否为字符
调用了public Integer(String s)创造对象
调用了intValue()方法返回一个整数[3]
2) p.removeSong(Integer.parseInt(position));
将字符串参数作为有符号的十进制整数进行解析。返回10进制的整数 见[3]
小结:
读取数字用到两个类
BufferedReader
InputStreamReader
public static BufferedReader input;
input = new BufferedReader(new InputStreamReader(System.in));
input = readLine();
int position
position = Integer.parseInt(input);
2.http://zhidao.baidu.com/question/124694500.html 各位大是请问这句话如何理解BufferedReader br=new BufferedReader(new InputStreamReader(System.in));百度知道
3.http://www.cjsdn.net/Doc/JDK60/java/lang/Integer.html#Integer(java.lang.String) java CSDN jdk6.0 中文版 Integer类