我正在开发一个程序,将显示三个选项:
- 将十进制转换为二进制
- 将二进制转换为十进制
- 退出。
如果用户选择“退出”,系统会接受该选项并说“再见”。
目前我的代码如下:
import java.util.Scanner;
public class binary {
public String toBinary(int n) {
if (n == 0) {
return "0";
}
String binary = "";
while (n > 0) {
int rem = n % 2;
binary = rem + binary;
n = n / 2;
}
return binary;
}
public static int binaryTodecimal(int i) {
int n = 0;
for (int pow = 1; i > 0; pow *= 2, i /= 10)
n += pow * (i % 10);
return n;
}
public static void main(String[] args) {
int answer2 = 0;
String answer;
final int info = 10;
for (int i = 0; i < info; i++) {
Scanner kb = new Scanner(System.in);
System.out.println("==================================");
System.out.print("Enter your choice: ");
answer = kb.next();
if (answer.equalsIgnoreCase("3"))
System.exit(0);
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
binary decimalToBinary = new binary();
String binary = decimalToBinary.toBinary(answer2);
if (answer.equals("1"))
System.out.println("The 8-bit binary representation is: " + binary);
binary bd = new binary();
int n = bd.binaryTodecimal(answer2);
if (answer.equals("2"))
System.out.println("The decimal representation is: " + answer2);
我正在遇到的问题是这样的。
In trying to convert the number in answers2 to binary or decimal, I cannot figure out how to actually split the answer2 up for this to work. I thought of doing a loop, but not sure what else I can do. Could you by chance tell me what I need to do? I'm new in Java, still trying to learn the ropes.
In converting decimal to binary, its printing out 6-bit or another bit, I want it specifically to be 8-bit. How can I fix this? Example:
Enter your choice: 1 Enter a number: 16 The 8-bit binary representation is: 10000
answer2
是一个整数。因此它已经是二进制的了。你需要从十进制开始,这意味着需要使用字符串。 - user207421int
视为其中之一的处理在尝试编写转换程序时都有些误导性。只有当二进制和十进制表示均作为字符串处理时,才能得到忠实的算法(其中不会隐式进行任何转换)。 - Linus