Reputation: 19
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
Reputation: 2876
If you insist on using your own code, you should maybe take in mind following things:
toCharArray()
method. This gives you a char[]
, which will also be more useful in the rest of your programval
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?Integer.parseInt(String s)
if you use literals in your numbers. It should throw a NumberFormatException
.Upvotes: 1
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
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