Question: Can you rewrite my program so that it doesn't use any of JAVA's built in base conversions? I ' m not allowed to use them

Can you rewrite my program so that it doesn't use any of JAVA's built in base conversions? I'm not allowed to use them and I can't figure out how to do it.
import java.math.BigInteger;
import java.util.Scanner;
public class converter {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Base Conversions Program!");
String value;
int initialBase, finalBase;
if (args.length ==3){
value = args[0];
initialBase = Integer.parseInt(args[1]);
finalBase = Integer.parseInt(args[2]);
} else {
System.out.print("Enter the value to convert: ");
value = scanner.next();
System.out.print("Enter the initial base: ");
initialBase = scanner.nextInt();
System.out.print("Enter the final base: ");
finalBase = scanner.nextInt();
}
if (isValidInteger(value, initialBase)){
String result = convertInteger(value, initialBase, finalBase);
System.out.println("Result: "+ result);
} else {
System.out.println("Error: Invalid input for the specified base.");
}
}
public static boolean isValidInteger(String theValue, int theBase){
// Check if theValue is a valid expression in theBase
for (char digit : theValue.toCharArray()){
int digitValue = Character.digit(digit, theBase);
if (digitValue ==-1|| digitValue >= theBase){
return false; // Invalid digit for the specified base
}
}
return true;
}
public static String convertInteger(String theValue, int initialBase, int finalBase){
// Convert theValue from initialBase to finalBase
BigInteger decimalValue = convertToDecimal(theValue, initialBase);
return convertFromDecimal(decimalValue, finalBase);
}
private static BigInteger convertToDecimal(String value, int base){
BigInteger decimalValue = BigInteger.ZERO;
BigInteger baseValue = BigInteger.ONE;
for (int i = value.length()-1; i >=0; i--){
int digit = Character.digit(value.charAt(i), base);
decimalValue = decimalValue.add(baseValue.multiply(BigInteger.valueOf(digit)));
baseValue = baseValue.multiply(BigInteger.valueOf(base));
}
return decimalValue;
}
private static String convertFromDecimal(BigInteger decimalValue, int base){
StringBuilder result = new StringBuilder();
while (decimalValue.compareTo(BigInteger.ZERO)>0){
BigInteger[] quotientAndRemainder = decimalValue.divideAndRemainder(BigInteger.valueOf(base));
BigInteger quotient = quotientAndRemainder[0];
BigInteger remainder = quotientAndRemainder[1];
result.insert(0, remainder.toString(base));
decimalValue = quotient;
}
return result.toString();
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!