Question

In: Computer Science

Design and implement a method that will take any value as String (even it's a number!)...

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.

i am using blue j / java, can you please provide a solution for the above with explaining comments  

thank you

Solutions

Expert Solution

NOTE:If you are stuck somewhere feel free to ask in the comments....I will try to help you out...but do not give negative rating to the question as it affects my answering rights........

Also note the code is explained in comments.....walk carefully through the code to understand the working

Iam assuming you know the basic conversions from one base to another...

//NOTE the idea is simple 
//First we see that if both the source and the destination base are the same , if so no need to convert
//next step is probably the most important
//we need to change the given string to decimal format if not in the decimal base
//this is done by calling getDecimal() function
//once we convert it to decimal the idea is simple of dividing the decimal no by required base to get remainder 
//check that remainder with appropriate conditions
//and then move on to next iteration
import java.io.*;
import java.util.*;
public class BasetoBase{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the number: ");
        String n = br.readLine();
        n = n.toUpperCase();
        System.out.print("Source base: ");
        int s = Integer.parseInt(br.readLine());
        System.out.print("Destination base: ");
        int d = Integer.parseInt(br.readLine());
        ArrayList<String> res = convertToBase(n, s, d);
        System.out.println(res);
    }
    public static ArrayList convertToBase(String n, int b1, int b2){
        if(b1 == b2){//if base is same
            ArrayList<String> result=new ArrayList<String>();
            for(int i=0;i<n.length();i++){
                char c=n.charAt(i);
                result.add(Character.toString(c));
            }
            return result;
        }
            
        int deci = 0;
        if(b1 != 10)
            deci = getDecimal(n, b1);//if source base is not in decimal
        else
            deci=Integer.parseInt(n);//if already in decimal just convert to int format
        ArrayList<String> result=new ArrayList<String>();
        if(deci == 0)
            result.add("0");
        while(deci != 0){
            int d = deci % b2;//gets the remainder
            //now check for the following cases ....this might be the cases when converting to hexadecimal
            if(d < 10) 
                result.add(0,Integer.toString(d));
            else if(d == 10)
                result.add(0,"A");
            else if(d == 11)
                result.add(0,"B");
            else if(d == 12)
                result.add(0,"C");
            else if(d == 13)
                result.add(0,"D");
            else if(d == 14)
                result.add(0,"E");
            else if(d == 15)
                result.add(0,"F");
            deci /= b2;//before moving to next iteration update the decimal no
        }
        return result;//Arraylist storing the result
    }
    public static int getDecimal(String n, int base){
        int d = 0;
        int num = 0;
        int p = 0;
        for(int i = n.length() - 1; i >= 0; i--){
            char ch = n.charAt(i);
            switch(ch){
                case '0':
                num = 0;
                break;
                case '1':
                num = 1;
                break;
                case '2':
                num = 2;
                break;
                case '3':
                num = 3;
                break;
                case '4':
                num = 4;
                break;
                case '5':
                num = 5;
                break;
                case '6':
                num = 6;
                break;
                case '7':
                num = 7;
                break;
                case '8':
                num = 8;
                break;
                case '9':
                num = 9;
                break;
                case 'A':
                num = 10;
                break;
                case 'B':
                num = 11;
                break;
                case 'C':
                num = 12;
                break;
                case 'D':
                num = 13;
                break;
                case 'E':
                num = 14;
                break;
                case 'F':
                num = 15;
                break;
            }
            d += num * (int)Math.pow(base, p);
            p++;
        }
        return d;
    }
}

Outputs:--->


Related Solutions

Please implement Sample string toString()method for each class and return itself a string, not the output....
Please implement Sample string toString()method for each class and return itself a string, not the output. import java.util.ArrayList; public class Customer extends User{ private ArrayList orders; public Customer(String display_name, String password, String email) { super(display_name, password, email); } @Override public String getPermissionLevel() { return "CUSTOMER"; } public void addOrder(Order order){ this.orders.add(order); } public ArrayList listOrders(){ return this.orders; }; } ---------------- public class ElectronicProduct extends Product{ private long SNo; private String warranty_period; public ElectronicProduct(long SNo, String warranty_period, String productId, String productName,...
This is my java method that is suppose to take data from a file(String, String, Double,...
This is my java method that is suppose to take data from a file(String, String, Double, Int ) and load that data into an object array. This is what I have and when I try to display the contents of this array it prints a "@" then some numbers and letters. which is not the correct output. any help correcting my method would be much appreciated. public void loadInventory(String fileName) { String inFileName = fileName; String id = null; String...
Draw a state diagram of the string pattern recognizer, implement it according to the design sequence...
Draw a state diagram of the string pattern recognizer, implement it according to the design sequence of the FSM, and draw a schematic diagram.
binarySearchLengths(String[] inArray, String search, int start, int end) This method will take in a array of...
binarySearchLengths(String[] inArray, String search, int start, int end) This method will take in a array of strings that have been sorted in order of increasing length, for ties in the string lengths they will be in alphabetical order. The method also takes in a search string and range of indexes (start, end). The method will return a String formatted with the path of search ranges followed by a decision (true or false), see the examples below. Example 1: binarySearchLengths({"a","aaa","aaaaa"},"bb",0,2) would...
Problem: Take 3 inputs string, integer, string. If incorrect number of lines are given then print...
Problem: Take 3 inputs string, integer, string. If incorrect number of lines are given then print an error message. Also have to make sure 2nd input is an integer and not a string by default. The function in the program should take the second string and insert it into the first string in the position indicated by the integer input given. The program cannot use strlen() or strncpy() functions and it should check the integer input to make sure it...
Java String search Design and implement a recursive version of a binary search.  Instead of using a...
Java String search Design and implement a recursive version of a binary search.  Instead of using a loop to repeatedly check for the target value, use calls to a recursive method to check one value at a time.  If the value is not the target, refine the search space and call the method again.  The name to search for is entered by the user, as is the indexes that define the range of viable candidates can be entered by the user (that are...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:   ...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:    Tune();    Tune( const string &n );      const string & get_title() const; }; class Music_collection { private: int number; // the number of tunes actually in the collection int max; // the number of tunes the collection will ever be able to hold Tune *collection; // a dynamic array of Tunes: "Music_collection has-many Tunes" public: // default value of max is a conservative...
- Design and implement a function with no input parameters. The function keeps receiving a number...
- Design and implement a function with no input parameters. The function keeps receiving a number from input (user) and adds the numbers together. The application keeps doing it until the user enter 0. Then the application will stop and print the total sum and average of the numbers the user had entered.
Design, implement, and fully test a Python3 function that converts a number to words (words_from_number(number: int))....
Design, implement, and fully test a Python3 function that converts a number to words (words_from_number(number: int)). It should expect to be passed a natural number (such as 12345) and return the corresponding words (i.e., “twelve thousand three hundred forty-five”). Since Python integers can grow arbitrarily large, your code should be flexible, handling at least 20 digits (realistically, it’s just as easy up to 30 digits). Spell everything correctly, and use correct punctuation (hyphens for forty-five and thirty-seven, no commas or...
Design, implement, and fully test a Python3 function that converts a number to words (words_from_number(number: int))....
Design, implement, and fully test a Python3 function that converts a number to words (words_from_number(number: int)). It should expect to be passed a natural number (such as 12345) and return the corresponding words (i.e., “twelve thousand three hundred forty-five”). Since Python integers can grow arbitrarily large, your code should be flexible, handling at least 20 digits (realistically, it’s just as easy up to 30 digits). Spell everything correctly, and use correct punctuation (hyphens for forty-five and thirty-seven, no commas or...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT