我应该写一个java程序,把二进制转换成十进制,把十进制转换成二进制,把十进制转换成十六进制,把十六进制转换成十进制。我已经做了第一个零件使用开关的情况下,它的工作,现在我卡在最后两个。这是我到目前为止所拥有的。
package java_project_gabriel;
import java.util.Scanner;
public class BinaryToDecimal {
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 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();
switch (answer) {
case "1": // if the answer is one do this action
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
BinaryToDecimal decimalToBinary = new BinaryToDecimal();
String binary = decimalToBinary.toBinary(answer2);
System.out.println("The 8-bit binary representation is: " + binary);
break; // leave the switch
case "2": // if answer is 2 do the following actions
System.out.print("Enter a number: ");
answer2 = kb.nextInt();
BinaryToDecimal bd = new BinaryToDecimal();
int n = bd.binaryTodecimal(answer2);
System.out.println("The decimal representation is: " + n);
break; // leave the switch case
case "3": // when the answer is 3
System.out.println("Goodbye");
System.exit(0);
// break; you need not use here because you have an exit call
}
}
}
}发布于 2021-10-28 15:54:29
十进制->十六进制:
public static String toHex(int decimal) {
int rem = 0;
String hex = (decimal == 0 ? "0" : "");
String hexstring = "0123456789ABCDEF";
while (decimal > 0) {
rem = decimal % 16;
hex = hexstring.charAt(rem) + hex;
decimal /= 16;
}
return hex;
}十六进制->十进制:
public static int toDecimal(String hex) {
String hexstring = "0123456789ABCDEF";
hex = hex.toUpperCase();
int num = 0;
for (int i = 0; i < hex.length(); i++) {
char ch = hex.charAt(i);
num = 16 * num + hexstring.indexOf(ch);
}
return num;
}https://stackoverflow.com/questions/69756832
复制相似问题