使用 Buffered Reader 读取 int

Reading an int using Buffered Reader

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("please enter the size of array");
size = br.read();
sarray = new int[size];

for (int i = 0; i < size; i++) {
    sarray[i] = i;
}
System.out.println(sarray.length);

当我尝试打印数组的长度时,它显示为“51”,即使我给出的大小为“3”。

BufferedReader.read() 读取单个字符并 returns 将其作为整数(即​​ returns 字符的 ASCII 码)。

当您输入 3 到您的 BufferedReader 时,read() 会将其读取为一个字符,即 '3',对应于 ASCII 码 51。

您可以通过执行以下代码来验证这一点:

System.out.println((int) '3'); // prints 51

使用 readLine() 方法而不是 read() 方法。

int size = Integer.parseInt(br.readLine());

read() 方法不return 输入的确切 int 值。

public int read() throws IOException Reads a single character. Overrides: read in class Reader Returns: The character read, as an integer in the range 0 to 65535 (0x00-0xffff), or -1 if the end of the stream has been reached Throws: IOException - If an I/O error occurse

参考:http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#read()