Java 扫描器 nextInt(16) 不接受负十六进制值

标签 java int hex

我需要读取十六进制格式的 32 位数字。当我输入负值时,出现输入不匹配异常。只要数字是正数(00000000 ~ 7FFFFFFF),一切都有效,但任何负数(80000000 ~ FFFFFFFF)都会失败。

     System.out.println("Enter first number in hexadecimal format: ");
     Scanner readX = new Scanner(System.in);
     int a = readX.nextInt(16);

我尝试了各种格式(FFFFFFFF、0xFFFFFFFF、-FFFFFFFF、-7FFFFFFFF、~FFFFFFFF),但结果相同。

有什么想法吗?我觉得我一定错过了一些明显的东西,但我完全被难住了!

最佳答案

它会因为同样的原因而失败 2147483648(比 Integer.MAX_VALUE 多一个)对于 Integer.parseInt 也会失败:该值为太大了。它不会将 ffffffff80000000 解释为负数,而是解释为较大的正数。这些数字太大,无法解释为 int

Scanner.nextInt(int radix)匹配正则表达式以查看它是否可能是 int,然后将其传递给 Integer.parseInt 进行解析:

If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix.

Integer.parseInt如果无法表示为 int,则会抛出 NumberFormatException:

An exception of type NumberFormatException is thrown if any of the following situations occurs:

  • The first argument is null or is a string of length zero.

  • The radix is either smaller than Character.MIN_RADIX or larger than Character.MAX_RADIX.

  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.

  • The value represented by the string is not a value of type int.

您必须指定该数字为负数。尝试 -1-80000000 或介于两者之间的任何值;他们会工作的。

关于Java 扫描器 nextInt(16) 不接受负十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20127477/

相关文章:

java - 如何在 kotlin 中将字符串中的运算符号设置为 int

c++ - 如何将字符串中的多个数字转换为整数

objective-c - 如何使用 Objective C 使用 Bluebamboo 设备打印图像?

python - Matlab num2hex 的 C++/Python 等效项

python argparse 十六进制错误

java - 如何使用脚本通过Java API更新elasticsearch文档中的一个字段?

Java 和 If 语句

c# - 为什么对 int 使用十六进制文字?

java - 使用 Spring Data 预填充数据

java - 无法在 Jzy3d 程序的子模块上执行目标 Maven Surefire 插件