有人可以帮助理解下面的程序。
import java.io.BufferedInputStream;
import java.io.IOException;
public class CmdReader {
public static void main(String []args) {
try (BufferedInputStream bis = new BufferedInputStream(System.in)) {
System.out.print("Enter age: ");
int age = bis.read();
System.out.println("Hello, you are " + age);
} catch(IOException e) {
e.printStackTrace();
}
}
}
输出:
Enter age: 12
Hello, you are 49
无法理解为什么打印 49 而不是 12。
非常感谢您的帮助。
最佳答案
49
是数字 1
的 ASCII 代码。您的代码正在读取仅第一个字符,并将其分配给int
使用该字符的值——它不会将其转换为它所代表的数字。您应该考虑使用 Scanner或其他一些解析值的方法; BufferedInputStream
只读取数据,没有别的。
关于java - 从 InputStream 捕获的值无法在 Java 中正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40825327/