黑马程序员技术交流社区

标题: [已解决]请教一个问题 [打印本页]

作者: 胡宝林    时间: 2012-6-5 18:40
标题: [已解决]请教一个问题
本帖最后由 hy19985125 于 2012-6-6 06:11 编辑

public class C{
    public static void main(String[] args) throws Exception{
   int x= System.in.read();
   while(x!='a'){
    System.out.println(x);
    x=System.in.read();
   }
}
}
程序循环的读取键盘上的字符,直到输入a后终止循环,
当输入b,并且按回车的时候,屏幕打印出了98,13,10
98代表的是b,13代表\r,  10代表\n
我的问题是一次循环打印一次x的值,为什么这一次打印了三个值
难道是循环了3次?求高手讲解!!!
作者: 吴小铁你好    时间: 2012-6-5 18:49
本帖最后由 吴小铁你好 于 2012-6-5 18:57 编辑

因为当你输入b后,你要按确认键,而xp系统的确认键位\r\n.
所以就打印了98,13,10.

可以改为:
public class C
{
    public static void main(String[] args) throws Exception
    {
    int x= System.in.read();
    while(true)
    {
      
     
      if(x=='\r'||x=='\n')
      {
       break;
      }
      else
      {
       System.out.println(x);
      }
     
    }
   
   }
}
作者: 武剑峰    时间: 2012-6-5 19:07
本帖最后由 武剑峰 于 2012-6-5 19:16 编辑

xp系统的回车键的值为\r\n  所以那怕你直接敲回车都会输出
13
10
代码改成如下就可以了
public class putInprint {
public static void main(String[] args) throws Exception {
  int x = System.in.read();
  while (x != 'a' ) {  
   if(x!='\r' && x!='\n')                 //回车不打印
    System.out.println(x);
  x = System.in.read();
  
  }
}
}


作者: 潘东升    时间: 2012-6-5 19:49
哈哈,就是循环了三次,你把循环去掉,读取了之后直接打印试试就知道了
作者: 张洁    时间: 2012-6-5 20:40
lz xp系统有个小常识哦~~
b = 退格
\n = 换行
\r = 回车
所以当你按确认键的时候,就会打印出来三个值~~~
代码可以改为:
public class C{
    public static void main(String[] args) throws Exception{
              int x= System.in.read();
              while(x!='a'){
                    if(x!='\r' && x!='\n')  {
                            break;}
                    else{  
                      System.out.println(x);}
             }
      }
}
作者: 李春阳    时间: 2012-6-5 20:42
因为还有你看不见的“输入”:
比如: 数值    8、    9、     10、  13
分别对应为  退格符、制表符、换行符、回车符
对应           b、    /t、    /n、   /r

而XP输入回车的时候等于输入一个/r /n
因而最终会多输出一个13、10

可以把代码修改一下:
public class C{
   public static void main(String[] args) throws Exception{
     int x= System.in.read();
     while(x!='a'){
       x=System.in.read();
       switch(x) {
       case !='/r':
          break;
       case !='/n':
          break;
       default:
          System.out.println(x);
       }  
     }
   }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2