gpt4 book ai didi

java - System.out.println 的未知输出

转载 作者:行者123 更新时间:2023-12-03 02:00:05 26 4
gpt4 key购买 nike

我正在学习 Java,在研究 try catch 循环时,我遇到了这种奇怪的行为。

无论我向以下代码提供什么数字,它都会返回 49 - 53 之间的数字。

public class demo{
public static void main(String[] args) {
System.out.println("Enter a number");
try{
int num = System.in.read();
System.out.println(num);
}catch(Exception e){
e.printStackTrace();
}
}
}

最佳答案

您必须输入数字 1-5。 read() method of InputStream (System.in 是一个 InputStream)以 int 形式返回字节值,但该值是 Unicode 代码。字符'1''5'由代码49-53表示。事实上,'0''9' 由代码 48-57 表示。

不要直接在InputStream上调用read。它适用于低级流处理。相反,将 InputStream 包装在 Scanner and call nextInt() 中.

关于java - System.out.println 的未知输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com