本帖最后由 唐林渊 于 2012-3-22 09:17 编辑
崩溃啦 大家帮忙解释下 我是后面学 前面忘的.
import java.io.IOException;
/*
* 设计方法,使用System.in.read()读取一行.循环读取一个字节,读取到\r\n结束。
* abc\r\ndef\r\n
*/
public class Exercise4 {
public static void main(String[] args) throws IOException {
System.out.println(readLine());
System.out.println(readLine());
System.out.println(readLine());
}
public static String readLine() throws IOException{
StringBuilder sb = new StringBuilder();
while(true){
byte b = (byte) System.in.read(); // 从键盘输入读取一个字节 <1>
if(b == '\r') // 判断如果是\r或\n, 就代表遇到了行末尾
continue;
if(b == '\n')
break;
if(b < 0){ // 如果小于0, 代表是中文
byte b1 = (byte)System.in.read(); // 再读一个字节
byte[] arr = {b, b1}; // 把2个字节装入一个数组
String s = new String(arr); // 将数组转为字符串
sb.append(s); // 添加到StringBuilder
}else
sb.append((char)b); // 如果不是\r或\n, 就用StringBuilder存起来 <2>char??
}
return sb.toString();
}
}
第一问
< 1>这个地方为什么强转为byte类型,别的类型不可以吗?就比如说直接转为char,<2>不是不用转了吗? 还有<2>为什么要转为char??
还有就是
byte b = (byte) System.in.read(); //这个已经转化为字节了
if(b == '\r') // 字节和字符可以进行比较吗? '\r'是字符类型吧
continue;
if(b == '\n')
break;
|