我尝试检查与此问题接近的其他问题,但无法找到适合我的答案,这就是为什么将其作为新帖子发送的原因。希望这不会造成任何问题。
我正在尝试编写一个简单的JAVA代码来进行数字转换——从十进制到八进制或十六进制。对于八进制,一切都很好,但是对于十六进制,输出的顺序错误。就像如果答案是 613 - 程序给出 316。
这是我的完整代码:
import java.util.Scanner;
public class Cem {
public static void octalconverter(int a) {
if (a == 0) { //our base
System.out.println(); //I first put here return a, but then it was adding zeros to the end
} else {
System.out.print(a % 8);// first remainder = last digit, and so on
octalconverter(a / 8); //recursively going till it is base
}
}
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}
public static String hexchart(int a) {
String result = "";
if (a <= 9) {
result = a + result;
} else {
if (a == 10)
result = result + "A";
// System.out.print("A");
if (a == 11)
result = result + "B";
// System.out.print("B");
if (a == 12)
result = result + "C";
// System.out.print("C");
if (a == 13)
result = result + "D";
//System.out.print("D");
if (a == 14)
result = result + "E";
//System.out.print("E");
if (a == 15)
result = result + "F";
// System.out.print("F");
}
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner oScan = new Scanner(System.in);
System.out.println("Please enter your decimal number : "); //getting input
int num = oScan.nextInt(); //assigning
System.out.println("Enter 1 for Octal Base Conversion #### Enter 2 for Hex Conversion");
int num2 = oScan.nextInt();
if (num2 == 1) {
System.out.print(num + " in Octal(base8) system is : ");
octalconverter(num); //conversion
} else if (num2 == 2) {
System.out.print(num + " in Hexadecimal(base16) system is : ");
hexconverter(num);
} else {
System.out.println("You entered a wrong choice for conversion type, please restart the program");
}
}
}
你能告诉我我哪里搞砸了吗?我还必须说我正在寻找我在这里犯的错误,而不是另一种编写此代码的方法。感谢那些愿意分享另一种方式的人,但我再次需要在这里学习我的错误。 谢谢您的帮助
最佳答案
改变
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
System.out.print(hexchart(a % 16));
hexconverter(a / 16);
}
}
至
public static void hexconverter(int a) {
if (a == 0) {
System.out.println();
} else {
hexconverter(a / 16);
System.out.print(hexchart(a % 16));
}
}
您的八进制转换也无法正常工作。它以相反的顺序打印。所以也只是交换了这些指令。
关于递归中的 Java decToHex - 错误的输出顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40026086/