如何在Java中手动创建一个将十进制转换为其他基数的方法?
我有一位教授不允许我使用简单的方法将十进制转换为其他基数(二进制、十六进制和八进制)。为此,我必须创建自己的方法如何在Java中手动创建一个将十进制转换为其他基数的方法?,java,math,methods,decimal,jgrasp,Java,Math,Methods,Decimal,Jgrasp,我有一位教授不允许我使用简单的方法将十进制转换为其他基数(二进制、十六进制和八进制)。为此,我必须创建自己的方法 public static String base(int num, int base) { String output = ""; while (num != 0) { int value = num % base; output = getDigit(value) + output; num = num / base; } re
public static String base(int num, int base)
{
String output = "";
while (num != 0)
{
int value = num % base;
output = getDigit(value) + output;
num = num / base;
}
return output;
}
public static char getDigit(char n)
{
{
switch (n)
{
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10: return 'A';
case 11: return 'B';
case 12: return 'C';
case 13: return 'D';
case 14: return 'E';
case 15: return 'F';
default:
System.out.println("Wrong key inputted!");
}
}
return n;
请注意,我犯了很多错误。
我不知道该从这里走到哪里。Java的Integer类具有内置函数来返回字符串、十六进制、二进制和八进制。希望这有帮助 更新 您的逻辑正确且有效,但代码中几乎没有错误,请查看:
public class Convert {
public static String base(int num, int base)
{
String output = "";
while (num != 0)
{
int value = num % base;
output = Convert.getDigit(value) + output;
num = num / base;
}
return output;
}
public static char getDigit(int n)
{
switch (n)
{
case 0: return '0';
case 1: return '1';
case 2: return '2';
case 3: return '3';
case 4: return '4';
case 5: return '5';
case 6: return '6';
case 7: return '7';
case 8: return '8';
case 9: return '9';
case 10: return 'A';
case 11: return 'B';
case 12: return 'C';
case 13: return 'D';
case 14: return 'E';
case 15: return 'F';
default:
System.out.println("Wrong key inputted!");
}
return ' ';
}
public static void main(String ...args){
System.out.println(Convert.base(Integer.parseInt(args[0]),Integer.parseInt(args[1])));
}
}
原始海报特别指出:“我有一位教授不允许我使用简易方法将十进制数转换为其他基数…”你的解决方案似乎是“简易方法”之一,因为这位教授似乎试图教授一堂关于实现算法的课。我在这里和那里跳过了几个词…:很明显,你在做dec到hex,但不太明显的是你的具体困难是什么。您的教授正试图训练您正确思考,因此请思考以下问题:“如果我向陌生人寻求帮助,我需要提供哪些信息才能获得帮助?”查看以了解更多信息。您是否使用IDE?如果是这样,它应该指出数据类型不匹配。如果没有,您应该开始使用一个,比如Eclipse。您的
getDigit
逻辑可以改进,比如returnn<10?“0'+n:'A'+n-10代码>就足够了。