用java写一个进制转换的函数: convert(int n ):输入一个十进制数n,将它转换成R进制数输出。

2024-11-12 11:13:03
推荐回答(4个)
回答1:

将十进制数N转换为r进制的数,其转换方法利用辗转相除法:以N=3456,r=8为例转换
以下是核心代码,如果需要完整源文件的,留个邮箱给我。
package src;

import javax.swing.JOptionPane;

public class NumberConvert {
public static void main(String args[])
{
LinkedStack stack = new LinkedStack(); //创建空栈
String inputstr;
char charremainder;
int sourcedecimalnumber,conversion,remainder,business;
do
{
try
{
inputstr=JOptionPane.showInputDialog("请输入你需要转换的十进制数:");
sourcedecimalnumber=Integer.parseInt(inputstr);
break;
}
catch (NumberFormatException exception)
{
JOptionPane.showMessageDialog(null,"请输入数字(十进制数)!","提示信息",0);
}
}while(true);

do
{
try
{
do
{
inputstr=JOptionPane.showInputDialog("请输入你需要转换进制(2~16之间的进制数):");
conversion=Integer.parseInt(inputstr);
if (conversion>1 && conversion<17)
break;
else
JOptionPane.showMessageDialog(null,"请输入2~16以内的数字!","提示信息",0);
}while (true);
break;
}
catch (NumberFormatException exception)
{
JOptionPane.showMessageDialog(null,"请输入数字(所要转换的进制数)!","提示信息",0);
}
}while(true);

business=sourcedecimalnumber;
while(business!=0)
{
remainder=business%conversion;
if(remainder>9)
remainder+=55;
else
remainder+=48;
charremainder=(char)remainder;
char [] chararray={charremainder};
stack.push(new String(chararray));
business/=conversion;
}

while(!stack.isEmpty())
{
System.out.print(stack.pop());

}
}
}

回答2:

public static String convertToBinary(int num){
return Integer.toBinaryString(num);
}
public static String convertToHex(int num){
return Integer.toHexString(num);
}
public static String convertToOctal(int num){
return Integer.toOctalString(num);
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println( convertToBinary(8) );
System.out.println( convertToHex(18) );
}

回答3:

Integer.toString(i, radix)

回答4:

你的R在哪?