我想将字符串格式的十进制数转换为二进制数。例如我想读取 2
并输出 10
。
我尝试过:
Scanner input = new Scanner(System.in);
String dec;
dec = input.next();
int bin = Integer.parseInt(dec, 2);
System.out.println(bin);
输入 2 时出现以下错误:
Exception in thread "main" java.lang.NumberFormatException: For input string: "2" under radix 2
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:665)
at binarytest.BinaryTest.main(BinaryTest.java:23)
最佳答案
如commented by Ole V.V. ,从用户处获取一个int
:
Scanner scanner = new Scanner( System.in );
int input = scanner.nextInt() ;
String output = Integer.toBinaryString( input ) ;
引用another wise comment作者:Ole V.V.:
It’s a good exercise in distinguishing between a concept and its representation in the UI. Here the number is the concept. In the UI it’s represented either as a decimal number (on input) or a binary number (on output). Use an
int
for the concept of a number and forget whether it’s binary, decimal or something else, those are implementation details not relevant to the task at hand. And apply the proper conversions on input and output.
关于java - 将 String 中提供的十进制数转换为二进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75839796/