for loop - Parsing a string to a Java method -


i'm new java, i'm sorry if answer seems obvious...

i've written method in class follows:

private static final string[] rcode = {"m", "cm", "d", "cd", "c", "xc", "l", "xl", "x", "ix", "v", "iv", "i"}    private int getcharvalue(string code)   {     // loop through codes find     // matching code, if found exit loop (via return).     (int position = 0; position < rcode.length; position++)     {       if (rcode[position] == code)         return rval[position];     } //      // otherwise return 0     return 0;   } // getcharvalue 

in method of same class looping through characters of string follows:

string number = "mmmcdxxxiv";  (int pos = 0; pos < number.length(); pos++) {    system.out.println(number.substring(pos, pos + 1) + " " + getcharvalue(number.substring(pos, pos + 1))); } // 

my problem while getcharvalue() method works fine when hardcode value in, e.g. getcharvalue("x") not work when call getcharvalue(number.substring(pos, pos + 1)) (even though know number.substring(pos, pos + 1) returning single characters should returning values.

can see obvious mistake?

many thanks...

if (rcode[position] == code) 

that not want in java. it's not comparing if characters make string same, it's comparing if 2 string objects same object. works when compare 2 compile time literals, because compiler smart enough point them same internal object. however, when generate new strings @ runtime, fail.

you want do:

if (rcode[position].equals(code)) 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -