Possible Duplicate:
How do I compare strings in Java?
I'm fairly new to Java and to practice I'm trying to create a hexadecimal to decimal number converter since I've successfully managed to make a binary to decimal converter.
The problem I'm having is basically comparing a given character of in a String with another string. This is how I define the current character that is to be compared:
String current = String.valueOf(hex.charAt(i));
This is how I try to compare the character:
else if (current == "b")
dec += 10 * (int)Math.pow(16, power);
When I try to run the code by entering just numbers e.g. 12, it works but when I try to use a 'b', I get a weird error. Here is the entire result of running the program:
run:
Hello! Please enter a hexadecimal number.
2b
For input string: "b" // this is the weird error I don't understand
BUILD SUCCESSFUL (total time: 1 second)
Here is an example of successfully running the program with just a number conversion:
run:
Hello! Please enter a hexadecimal number.
22
22 in decimal: 34 // works fine
BUILD SUCCESSFUL (total time: 3 seconds)
Any help with this would be appreciated, thanks.
Edit: I think it will be useful if I put the entire method here.
Edit 2: SOLVED! I don't know who's answer that I should accept though because they were all so good and helpful. So conflicted.
for (int i = hex.length() - 1; i >= 0; i--) {
String lowercaseHex = hex.toLowerCase();
char currentChar = lowercaseHex.charAt(i);
// if numbers, multiply them by 16^current power
if (currentChar == '0' ||
currentChar == '1' ||
currentChar == '2' ||
currentChar == '3' ||
currentChar == '4' ||
currentChar == '5' ||
currentChar == '6' ||
currentChar == '7' ||
currentChar == '8' ||
currentChar == '9')
// turn each number into a string then an integer, then multiply it by
// 16 to the current power.
dec += Integer.valueOf(String.valueOf((currentChar))) * (int)Math.pow(16, power);
// check for letters and multiply their values by 16^current power
else if (currentChar == 'a')
dec += 10 * (int)Math.pow(16, power);
else if (currentChar == 'b')
dec += 11 * (int)Math.pow(16, power);
else if (currentChar == 'c')
dec += 12 * (int)Math.pow(16, power);
else if (currentChar == 'd')
dec += 13 * (int)Math.pow(16, power);
else if (currentChar == 'e')
dec += 14 * (int)Math.pow(16, power);
else if (currentChar == 'f')
dec += 15 * (int)Math.pow(16, power);
else
return 0;
power++; // increment the power
}
return dec; // return decimal form
}