62,612
社区成员
发帖
与我相关
我的任务
分享
/**
* 2008年10月7日10:41:02
* \n 与 \r 的区别
*/
import java.io.IOException;
class M {
public static void main(String[] args) {
int ch = (int)'\r';
System.out.printf("ch = %d\n", ch);
ch = (int)'\n';
System.out.printf("ch = %d\n", ch);
System.out.println("请输入一串字符:");
while (true) {
try {
ch = (int)System.in.read();
} catch(IOException e) {
}
System.out.printf("ch = %d",ch);
}
}
}
/**
* 2008年10月7日10:55:22
* 编程实现:把从键盘上输入的一串字符在显示器上
* 输出,如果输入的是byte,这4个字母,则程序退出
*/
import java.io.IOException;
public class ReadLine {
public static void main(String[] args) {
byte[] buf = new byte[1024];
int pos = 0;
int ch = 0;
String strInfo = null;
System.out.println("请输入一行字符:");
while (true) {
//读取一个字节的数据
try {
ch = System.in.read();
} catch (IOException e) {
}
// 要想使用IOException,必须加上
// import java.io.IOExcaption;
// 要使用Exception,则不需要导入,
// 因为Exception在java.lang包中
switch (ch) {
case '\r': //20行
break; //21行 如果把20 21行注释掉,则运行时输入byte回车键,程序是不会退出的,除非把24行的"byte"改为"byte\r", 才可以保证输入byte回车键,程序立即退出,因为在Windows系统中回车键是当做\r\n来处理的
case '\n':
strInfo = new String(buf, 0, pos); //把buf数组中索引从0开始的总共pos个元素取出来构造成一个String对象,
if (strInfo.equals("byte")) {//24行
return;
} else {
System.out.println(strInfo);
pos = 0;
break;
}
default:
buf[pos++] = (byte)ch; //ch是int类型,必须进行强制类型转化
}
}
}
}