首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 其他教程 > 系统运维 >

System.in.read()施用

2012-12-26 
System.in.read()使用system.in.read()方法的作用是从键盘读出一个字符,然后返回它的Unicode码。按下Enter

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()施用

结论:

用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 后等待输入

热点排行