java - 将 String 中提供的十进制数转换为二进制数

标签 java casting binary

我想将字符串格式的十进制数转换为二进制数。例如我想读取 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() ;

convert to binary string .

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/

相关文章:

java - SQL 和 JPA 错误

java - 获取 Facebook 好友个人资料详细信息

c++ - 访问内存映射寄存器

java - 检测 Android 应用程序中 for 循环内的按钮点击

java - 如何在 Liferay 中为自定义角色的布局添加 VIEW 权限

c++ - 传递接受 void * 的成员函数

java - Java 中的转换性能

c - 如何将内核中的数据写入二进制文件

c++ - 如何在十六进制字符数组中插入十六进制值

algorithm - 移动平均线是否保留二进制系统中和/计数商的分辨率?