users1141df
users1141df

Reputation: 19

How can I convert my input String to an integer with a base conversion

I want my code whenever I input a base from 2-36 , It can output a number which is decimal. here is my code

package code;

public class solution{
    public static int x2ten(String s, int base){

        String[] bits = s.split("");
        int result = 0;


        for(int i=0; i < bits.length; i++ ){




            int val = (Integer.parseInt(bits[bits.length-1-i])) * ((int)Math.pow(base,i));
                val = charToInt(Integer.parseInt(bits[bits.length-1-i]))* ((int)Math.pow(base,i));



            result += val;
        }
        return result;
    }

    public static int charToInt(char c){
        char[] characters = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G',
                'H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

        for(int j = 0; j<characters.length; j++){
            if(characters[j] == c){
                return j;
            }

        }
        return -1;
    }





    public static void main(String[] args)
    {
             System.out.println(x2ten("1101",2));
    }
}

There is a problem at first appear charToInt, it said that I should change charToInt(char c) to charToInt(int c). But whats purpose of charToInt is convert whatever I input a Character like 1A, then it can output 26 in decimal.

Upvotes: 0

Views: 122

Answers (3)

If you insist on using your own code, you should maybe take in mind following things:

  1. If you want to get an array for all characters in a string, use the toCharArray() method. This gives you a char[], which will also be more useful in the rest of your program
  2. What's the point of assigning a value to val if you never use that value and immediately get another value in there. Get rid of that first line. It doesn't seem to be very useful, does it?
  3. Be careful with Integer.parseInt(String s) if you use literals in your numbers. It should throw a NumberFormatException.

Upvotes: 1

Saurabh Rai
Saurabh Rai

Reputation: 361

If you can notice that in the function call to the function charToInt(), you are passing an integer as an argument but if you see the definition of your function, it is expecting a character.Hence it is suggesting you to change it to int. Hope this helps :)

Upvotes: 0

Bohemian
Bohemian

Reputation: 425073

This is a wheel that's already been invented:

public static int x2ten(String s, int base) {
    return Integer.parseInt(s, base);
}

I would advise deleting your method entirely in favour of the one from the JDK, which even has the same signature.

Upvotes: 2

Related Questions