`
uule
  • 浏览: 6307225 次
  • 性别: Icon_minigender_1
  • 来自: 一片神奇的土地
社区版块
存档分类
最新评论

System.in.read()使用

 
阅读更多

system.in.read()方法的作用是从键盘读出一个字符,然后返回它的Unicode码。按下Enter结束输入

看一下这个程序:

for(int j = 0; j < 5; j++) {
	                    System.out.println("INPUT:");
	                    char c = 0;
	                    try {
	                       c = (char) System.in.read();	                       
	                     } catch(IOException e){ 
	                    	 
	                     }
	                    if( c == '1') {
	                      System.out.println("OK!");
	                     }
	                  }

 假设我们输入1,结果:

INPUT:
1
OK!
INPUT:
INPUT:
INPUT:

啥原因?

 

一点一点Debug我们会发现,第二次时读到的字符其实是回车符\t,继续循环;第三次接受到的是换行符\n,也继续循环;第三次到Input出不动,等待我们继续循环。

第二次:


结论:

用System.in.read()时,我们在键盘上按下的任何一个键都会被当做是输入值,包括Enter键也会被当做是一个值!当我们按下Enter的时候,实际上发送两个键值:一个回车\t(13),一个是换行\n(10)

 

参考:http://www.360doc.com/content/07/1112/13/15458_818134.shtml

 

例子2 :

public static void main(String[] args)  {
  try {
      int i=System.in.read();
      System.out.println(i);
  } catch (IOException e) {
   e.printStackTrace();
  }
}

 
这里输入1,这返回结果是49
输入A,返回结果是65

 

例子3:

 public static void main(String[] args) throws Exception {  
     int[] x = new int[6];  
     Arrays.fill(x, 1);  
     for (int i = 0; i < x.length; i++) {  
         System.in.read();  
         System.out.println(x[i]);  
     }  
 }

 结果:

输出1  1  1 后等待输入

  • 大小: 19.6 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics