【问题标题】:System.in.read() is misbehaving when trying to enter integer value [duplicate]尝试输入整数值时 System.in.read() 行为异常[重复]
【发布时间】:2023-04-03 00:01:02
【问题描述】:

我正在尝试通过 System.in.read() 输入整数值。 但是当我读取值时,它给出了不同的输出 49 表示 1,50 表示 2 等等int e=(int)System.in.read(); System.out.print("\n"+e);

【问题讨论】:

  • 原因是System.in.read() 读取的是一个字符,而不是一个整数。因此,当您将 char '1' 转换为 int 时,您会得到 char '1' 的 ASCII 值,即 49。

标签: java input


【解决方案1】:

因为字符1(即char ch = '1')具有ASCII码49(即int code = '1'49)。

System.out.println((int)'1'); // 49

要修正您的示例,只需减去 0 的代码:

int e = System.in.read() - '0';
System.out.println(e); // 1

【讨论】:

  • 更好的是,不要使用read()
  • @Andreas 我同意,Scanner 更好,但这不是这个问题的范围。
【解决方案2】:

你正在用函数读取字符

System.in.read()

可以看到System.in.read()here的使用。另请查看here 如何从用户读取值。

【讨论】:

  • 没有"cast to int",因为read()返回int
  • 感谢@Andreas 的链接和更正。
【解决方案3】:

正如其他答案所提到的,System.in.read()int 的形式读入单个字符,如果没有要读入的输入,则-1 读入。这意味着使用System.in.read() 读入的字符将是ints,代表读取字符的ASCII值。

要从System.in 读取整数,使用Scanner 可能更容易:

Scanner s = new Scanner(System.in);
int e = s.nextInt();
System.out.print("\n"+e);
s.close();

或者,如果你想坚持使用System.in.read(),你可以使用Integer.parseInt(String)System.in.read()的字符输入中获取一个整数:

int e = Integer.parseInt("" + (char) System.in.read());
System.out.print("\n"+e);

Integer.parseInt(String) 将抛出一个 NumberFormatException 如果输入不是数字,你可以捕捉到。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多