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

(3) Implement the getNumOfNonWSCharacters() method. getNumOfNonWSCharacters() has a string as a parameter and returns the number...
(3) Implement the getNumOfNonWSCharacters() method. getNumOfNonWSCharacters() has a string as a parameter and returns the number of characters in the string, excluding all whitespace. Call getNumOfNonWSCharacters() in the main() method. (4 pts) Ex: Enter a sample text: We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes, more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue! You entered: We'll continue our quest in space....
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...
How am I supposed to implement a c_str method that returns a c string representation of...
How am I supposed to implement a c_str method that returns a c string representation of a String object? I need to return a csting representation of a string object. I am confused on what cstrings are and where to go. method signature is as follows: char* c_str();
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 a state machine to recognize if a binary string contains any occurrence of the sequence...
Design a state machine to recognize if a binary string contains any occurrence of the sequence “10101”. Is it possible to design this state machine with less states? By using Finite State machine designer. http://madebyevan.com/fsm/
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT