JAVA create a class Radix that is able to convert numbers between different radi
ID: 3867138 • Letter: J
Question
JAVA
create a class Radix that is able to convert numbers between
different radices (also known as bases) (for simplicity we
restrict the possible radices to 2, 3, 4, ... , 16). The
program should read in three variables from the console one
line after another; an integer, the source base, an integer,
the destination base, and a string. The program should
interpret the string as a number in source base and output
it as a number in destination base (using the source and
destination base number system). e.g. Say your source base
was 3 and the destination base was 5. Then if the string
was 21, then 12 should be printed. You do not need to
handle negative numbers.
Explanation / Answer
import java.util.Scanner;
public class Radix {
public static void main(String[] args) {
String inputNo;
String convertedNo;
int toBase, fromBase, intVal;
try {
//Reading the Number in String Fromat from Console
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number you want to convert");
//Reading the base of the Number
inputNo = scanner.nextLine();
System.out.print("Enter the base in which the number is given");
//Reading the Destination base of the Number
fromBase = scanner.nextInt();
System.out.print("Enter the base to which you want the number converted");
toBase = scanner.nextInt();
//Conversion of base
intVal = Integer.valueOf(inputNo, fromBase);
convertedNo = Integer.toString(intVal, toBase);
System.out.print("The converted number is " + convertedNo);
} catch (Exception e) {
System.out.print("Kindly give valid input and try again");
main(args);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.