这是我的作业,明天到期。我们必须在Bluej上编写一个带有Java的程序,其中一个数字必须转换为基数10,然后是另一种将数字从基数10转换为任何基数的方法。用户首先输入数字和基数,然后选择他们想要的方法。我正在为这个程序使用两个类:“Runner”和“Converter”。 My Runner类运行程序并询问用户输入什么,然后调用该方法。 Converter类有两种方法及其算法。 Runner类在下面,Convert类将在Runner下面:
import java.util.Scanner;
public class Runner
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
Converter calc = new Converter();
System.out.println("Enter a number ::");
int number = scan.nextInt();
System.out.println("Enter a base number ::");
int base = scan.nextInt();
System.out.println();
System.out.println("Press 1 to convert TO base 10.");
System.out.println("Press 2 to convert FROM base 10.");
int calculationKey = scan.nextInt();
if (calculationKey == 1)
{
System.out.println(calc.convertToTen(number, base));
}
else if(calculationKey == 2)
{
System.out.println(calc.convertToBase(number, base));
}
else
{
System.exit(0);
}
}
}
转换器类:
import java.util.Scanner;
public class Converter
{
private int remainder, exponent, length, answer;
public int convertToTen(int number, int base)
{
int num1 = number;
length=0;
while(number > 0 )
{
num1 = num1 / 10;
length++;
}
int length2 = length;
for (exponent = 0; exponent <= length2; exponent++)
{
remainder = number % 10;
answer = (remainder * (base ^ exponent));
answer++;
}
return(answer);
}
public int convertToBase(int number, int base)
{
int num1 = number;
while (number > 0)
{
number = number % base;
}
return remainder;
}
}