Java 使用缓冲读取器读取 int

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32715459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:59:13  来源:igfitidea点击:

Reading an int using Buffered Reader

javabufferedreader

提问by jellyFish

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);

When I tried to print the length of the array, it is showing as "51" even though i gave the size as "3".

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

采纳答案by Rehman

Use readLine() method instead of read() method .

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

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

read() method doesnt return the exact int value of input.

read() 方法不返回输入的确切 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

public int read() throws IOException 读取单个字符。覆盖:读取类 Reader 返回:读取的字符,为 0 到 65535 (0x00-0xffff) 范围内的整数,如果已到达流的末尾,则为 -1 抛出:IOException - 如果发生 I/O 错误

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

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

回答by Tunaki

BufferedReader.read()reads a single character and returns it as an integer (i.e. returns the ASCII code of the character).

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

When you input 3to your BufferedReader, read()will read it as a character, i.e. as '3', which corresponds to the ASCII code 51.

当你输入3你的BufferedReader,read()会将它读为一个字符,即 as '3',它对应于 ASCII 码 51。

You can verify this by executing the following code:

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

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