本资源引自: 关于JAVA中回车符的认识-Java认证考试-青年人网 http://www./pc/java/fudao/jichu/201007/499546.html ------------------------------------------------------------------------------------------------------------------------------------- 关于JAVA中回车符的认识 Java代码 1. 2./** 3. * 测试回车换行符:\r\n 4. * TestEnterWrap 5. * Author:广凌风 6. * Jul 8, 2010 9:25:34 AM 7. */ 8.public class TestEnterWrap { 9. 10. /** 11. * TestEnterWrap.main() 12. * @param args 13. * @return void 14. * Author:Junliang Lin 15. * Jul 8, 2010 9:25:12 AM 16. */ 17. public static void main(String[] args) throws Exception{ 18. System.out.print("Input a char:"); 19. 20. char ch = (char)System.in.read(); 21. 22. System.out.println("hello" + ch + "AB"); 23. 24. 25. 26. } 27. 28.} 编译并运行这个程序。 (1)在DOS下运行,输入字符“a”,命令行窗口打印输出的结果: helloaAB。 (2)在DOS下运行,直接按下回车键,在命令行窗口打印输出的结果:ABllo。 如下图: 解释如下: 读取键盘输入的一个字符时,我们在键盘上按一下回车键,实际上读取到的是两个字符,即“\r”和“\n”。字符“\r”表示回车,即光标回到当前行的行首而不换行;字符“\n”表示换行,即光标移到当前行的下一行行首。 按一下回车键,System.in.read()读取到字符“\r”,当执行到下面的程序代码时: System.out.println("hello" + ch + "AB"); 打印字符串“hello”后,接着打印输出字符“\r”,这时,光标移到字符串“hello”所在当前行的行首,由于没有字符“\n”,不会换到下一行,再继续打印字符串“AB”。这样,字符串“AB”就覆盖了字符串“hello”的前两个字符,所以,我们看到在命令行打印输出的是字符串“ABllo”。 在常用的IDE上运行该程序的时候,当我们在键盘上按一下回车键,实际上读取到的是两个字符,即“\r”和“\n”。 在eclipse下运行的结果为: hello AB 如下图: |
|
来自: bleach尸魂界 > 《Java 特殊符号》