Java——使用扫描仪读取十六进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5751217/
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
Java -- reading in hexadecimal numbers using a scanner
提问by farm ostrich
In Java, hexadecimal numbers may be stored in the primitive integer type.
在 Java 中,十六进制数可能以原始整数类型存储。
private static volatile final synchronized int x = 0x2FE;
However reading in a hex using the Scanner class's nextInt()
method throws an input mismatch exception. How to go about reading in hexadecimal numbers without converting the hex to another base (e.g. two or ten or whatever). THANKS.
但是,使用 Scanner 类的nextInt()
方法以十六进制读取会引发输入不匹配异常。如何在不将十六进制转换为另一个基数(例如,二或十或其他)的情况下读取十六进制数。谢谢。
EDIT:
编辑:
This code is throwing the same exceptions. What am I doing wrong here:
此代码抛出相同的异常。我在这里做错了什么:
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//scan.useRadix(16);
int[] input = new int[10];
for (int i = 0; i < 10; i++) {
//input[i] = scan.nextInt(16);
System.out.println(input[i]);
}
}
}
Thanks again.
再次感谢。
回答by Cory G.
Scanner class has this:public int nextInt(int radix)
扫描仪类有这个:public int nextInt(int radix)
If you put 16
as the radix, it will probably do what you want to do.
如果你把它16
作为基数,它可能会做你想做的事。
回答by WhiteFang34
If you do this:
如果你这样做:
int value1 = 0x2FE;
int value2 = new Scanner("2FE").nextInt(16);
Both value1
and value2
will be integer 766 in base 10.
都value1
和value2
将整数766在底座10。