英文:
Trouble with Java decimal to binary converter
问题
import javax.swing.*;
public class BinaryConverter {
public static void main(String[] args) {
char number;
int input, length;
String reversedBinary = "", binary = "";
input = Integer.parseInt(JOptionPane.showInputDialog("What number would you like converted to binary?"));
do {
reversedBinary = reversedBinary + "" + input % 2;
input = input / 2;
} while (input > 0);
length = reversedBinary.length();
length--;
while (length > 0) {
number = reversedBinary.charAt(length);
binary = binary + number;
length--;
}
System.out.print("The number converted to binary is: " + binary);
}
}
英文:
I am learning Java and have been trying to build this converter for more than a week, but this attempt sometimes leaves out a necessary 0 and also does not give a result for the input "1".
this code has imported javax.swing.*; // allows for "JOptionPane.showInputDialog", a request for typed information plus a message
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
}
}
答案1
得分: 0
以下是翻译好的代码部分:
input = Integer.parseInt(JOptionPane.showInputDialog("您想要转换为二进制的数字是多少?")); // 请求用户输入
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));
英文:
Something like this shall work.
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));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论