I need assistance writing this code. I keep generating errors and not sure what to do now.
Design and implement a method that will take any value as String (even it's a number!) and convert that value to a number in any base. Use the method;
private static ArrayList convertToBase(String value, int currentBase, int targetBase){
// your algorithm
return result; //which is a String array
}
Examples:
convertToBase("10011", 2, 10) should return [1, 9], meaning,
(10011)base2 = (19)base10
convertToBase("100", 10, 8) should return [6, 4]
convertToBase("E12B0", 16, 2) should return [1,1,1,0,0,0,0,1,0,0,1,0,1,0,1,1,0,0,0,0]
convertToBase("1250", 10, 16) should return [4, E, 2]
Write a tester, make sure your code produces correct results.
import java.util.*;
public class Demo{
public static ArrayList convertToBase(String value, int currentBase, int targetBase){
String str=Integer.toString(Integer.parseInt(value, currentBase), targetBase);
ArrayList<Character> result = new ArrayList<Character>();
for (char c : str.toCharArray()) {
result.add(Character.toUpperCase(c));
}
return result;
}
public static void main(String[] args){
System.out.println(convertToBase("10011",2,10));
System.out.println(convertToBase("100",8,10));
System.out.println(convertToBase("100",10,8));
System.out.println(convertToBase("E12B0",16,2));
System.out.println(convertToBase("1250",10,16));
}
}
Note:
->the output of convertBase("100",10,8) is [1,4,4]
->the output of convertBase("100",8,10) is [6,4]
It is given wrong in the question.
But i have printed both of the them
Below is the screenshot of the code for reference purpose:
output:
Get Answers For Free
Most questions answered within 1 hours.