import java.io.*;

public class BaseTransform
{
    private final BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));

    public BaseTransform(){
        try{
        System.out.print("Enter any integer: ");
        int input=Integer.parseInt(this.getInput());
        System.out.print("Enter a base[2...16]: ");
        int base=Integer.parseInt(this.getInput());
        String answer=this.transform(input,base);
        if(answer!=null){
            System.out.println(""+input+" at base "+base+" is "+answer+".");
        }else{
            System.out.println("Error!");
        }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String args[]){
        BaseTransform bt=new BaseTransform();
    }


    private String transform(int data,int base){
        if(base>16 || base<2)return null;
        String answer="";
        if(base==10){
            return ""+data; //base 10 is decimal
        }else{
            try{
                while((data/base)>0){
                    answer=this.checkResult((data%base),base)+answer;
                    data=data/base;
                }
                answer=this.checkResult((data%base),base)+answer;
                return answer;
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return null; //means error
    }

    private String checkResult(int digit,int base){
        //for bases greater than or equals 10 start printing letters
        if(base>=10){
            //we will analyze each digit if greater than 10 again
            if(digit>=10){
                return ""+(char)(digit-10+65);
            }
        }
        return ""+digit;
    }

    private String getInput(){
        try{
            return buffer.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        return null; //means error
    }
}

Recommended Answers

All 4 Replies

Please post your question not just your code expecting people will try to figure out what sort of errors you getting and what are you actually trying to achieve

first error: using magic return values to indicate success or failure is not a good idea.
Use the exception handling system instead.

i dont know what is the error i cannot run this one...
im only new in programming.

i dont know what is the error i cannot run this one...
im only new in programming.

Obviously if you not able to run this program that means that Java compiler found some errors in your code and you been supposed to posted this errors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.