java - Java十进制到二进制转换器的问题
问题描述
我正在学习 Java,并且已经尝试构建这个转换器一个多星期了,但是这种尝试有时会遗漏必要的 0,并且也不会为输入“1”给出结果。
此代码已导入 javax.swing.*;// 允许“JOptionPane.showInputDialog”,一个对输入信息的请求加上一条消息
public static void main(String[] args) {
// TODO Auto-generated method stub
char number;
int input, length;
String reversedBinary = "", binary = "";
input = Integer.parseInt(JOptionPane.showInputDialog
("What number would you like converted to binary?")); // Requesting user to give input
do { // gets the reversed binary. For instance: 5 = 101
reversedBinary = reversedBinary + "" + input % 2;
input = input/2;
} while (input > 0);
length = reversedBinary.length();
length--; // getting the usable position numbers instead of having length give me the position one ahead
while (length > 0) { // some code to reverse the string
number = reversedBinary.charAt(length);
binary = binary + number;
length--; // "reversedBinary" is reversed and the result is input into "binary"
}
System.out.print("The number converted to binary is: " + binary); // output result
}
}
解决方案
这样的事情会奏效。
input = Integer.parseInt(JOptionPane.showInputDialog
("What number would you like converted to binary?")); // Requesting user to give input
String BinaryStr="";
int i = 0;
while (input > 0){
BinaryStr= BinaryStr+ input % 2;
input = input/2;
i++;
}
for (int j = i - 1; j >= 0; j--)
System.out.print(BinaryStr.charAt(j));
推荐阅读
- arrays - 创建和操作数组数组
- python-3.x - 是否可以将 sklearn 估计器放在 sklearn.compose.ColumnTransformer 中?
- mongodb - 同一文档中和文档之间的 Concat 数组
- shopify - 无论如何要显示在shopify中提交联系表的用户?
- barcode - 如何使用带有校验位的 ZPL 创建 GS1-128 条码
- python - SQLAlchemy:为具有复合主键的单个表中的所有 id 选择最近的行
- python - 生成包含 3 个字典的所有组合的字典列表
- r - 如何将英里区域添加到 R 密度图?
- python - 我的程序运行时间过长时遇到问题。我不确定它是无限运行还是真的很慢
- c - C:如果我理解 0 和 '\0' 相同,那么当我编写 int my_array = {0}; 时,编译器如何知道数组的大小?