3

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
}
Community
  • 1
  • 1
moka
  • 65
  • 1
  • 1
  • 9
  • I think "Converting A String To Hexadecimal In Java" can be useful (http://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java) – Igor K Feb 05 '13 at 10:58
  • Hello @IgorK, I'm using another method to convert hexadecimal numbers to decimal. – moka Feb 05 '13 at 11:18

6 Answers6

12

Try initializing a char to the char value returned by charAt()

char current = hex.charAt(i);

Then in your conditional use the literal char:

else if (current == 'b') 

Since char is a primitive you can compare it using the == operator. In the former code you were comparing a String using ==, since a String is an Object the code is checking to see if they are the same Object not if they have the same value as the String.equals() method would.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • This didn't work but really, it should. I'm starting to think there might be something else wrong with my code now. Should I put the entire method in the original post? – moka Feb 05 '13 at 11:10
  • @Moka yes it is always good to post more code – Kevin Bowersox Feb 05 '13 at 11:41
  • @Moka Aren't hexadecimal numbers all uppercase? Your conditionals are checking against lowercase, so is mine. Might want to make it like `'B'` – Kevin Bowersox Feb 05 '13 at 11:51
  • I've made it so that the input is converted to lowercase. Your answer really helped, thanks a lot man. – moka Feb 05 '13 at 11:56
1

Without the full code it is difficult to be certain, but the "for input string: xx" form is usually the message associated with NumberFormatException. Are you converting (part of) the string to a number by using Integer.valueOf(), Integer.parseInt() or similar methods by chance?

If this is the case in order to have them accept an hexadecimal digit (a-f) you need to explicitly state you are passing in a 16-base digit, by calling the methods that accept a second parameter for the radix - e.g. Integer.valueOf(string, 16).

Also, like others pointed out already, the correct way to compare strings is to use the equals method, since the == operator will only return true if the two references points to the exact same object, regardless of its value (content).

Grim
  • 1,608
  • 9
  • 12
  • I have now posted the full method and yes I am using Integer.valueOf() a lot. – moka Feb 05 '13 at 11:25
  • That's the source of your error then. You could simply convert every digit to the corresponding int number using Integer.valueOf(hex.charAt(i), 16) as suggested above, but since that would defeat the point of your practice code, you might want to simply wrap the part where you convert the decimal digit with an if to make sure said digit is a valid decimal digit - i.e. `if ("0123456789abcdefABCDEF".contains(String.valueOf(hex.charAt(i)))` { // do the number-conversion here } – Grim Feb 05 '13 at 11:42
0

You need to compare strings with equals method

else if ("b".equals(current)) 

you can find more details here: http://www.javabeginner.com/learn-java/java-string-comparison

duffy356
  • 3,678
  • 3
  • 32
  • 47
0

Change your string to char. char current = hex.charAt(i);

Then in your else if you need to check for 'b' and 'B'

else if (current == 'b' || current == 'B') { }

Renjith
  • 3,274
  • 19
  • 39
  • I have already tried this as Kevin recommended but it didn't seem to work. It still just says `For input string: "b"`. – moka Feb 05 '13 at 11:12
  • Can you put the entire method here? – Renjith Feb 05 '13 at 11:16
  • I guess you are getting Number Format Exception from Integer.valueOf() method.Try comparing the characters direcly like:if(current == '0'),if(current == '1') like that.And inside if convert it to int – Renjith Feb 05 '13 at 11:33
0

Use .equals() to compare strings. When you use == i think it checks if they both reference same thing or not.

hope that helps. :)

0

Actually, there is a very simple and elegant way of doing it:

int result = Integer.parseInt(hex, 16);
Igor K
  • 470
  • 6
  • 10
  • Yes, this has already been established but it would defeat the point of my practice exercise. I am trying to learn Java and improve my skills. – moka Feb 05 '13 at 15:31