---
title: "System.in.read()使用"
author: "uule"
date: "2011-07-19T18:08:37Z"
tags: []
categories: ["编程语言"]
slug: "system-in-read"
draft: false
lastmod: "2011-07-19T18:18:10Z"
id: 1128243
url: "https://uule.iteye.com/blog/1128243"
---

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出不动，等待我们继续循环。

第二次：

![](http://dl.iteye.com/upload/attachment/520342/4bfcb91e-bb18-33b3-8040-f6ea951cf204.png)

**结论：**

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

 

参考：[http://www.360doc.com/content/07/1112/13/15458\_818134.shtml](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 后等待输入