Replace Symbols with Numbers in Java?

Discussion in 'Mac Programming' started by JOD8FY, Mar 21, 2007.

  1. macrumors 6502a

    JOD8FY

    Joined:
    Mar 22, 2004
    Location:
    United States
    #1
    Hello all,

    I have a question about how to replace symbols with numbers in Java. I know that this can be done with letters using replaceAll(), but it doesn't seem to work with symbols. What I'd like to do is convert 100.0? into 100.00. Essentially, I'm making the question mark a zero so that I can use the 100.00 to multiply, divide, etc. Here is a sample of my code (textToConvert and textConverted are both text fields):

    Code:
    if(e.getSource()==convert)
    {
    String line = textToConvert.getText();
    String replaced = line.replaceAll("?", "0");
    textConverted.setText(replaced);
    }
    This will compile fine, but when I enter, for instance, 100.0? into the textToConvert text field, it won't function at all; nothing is converted and nothing is placed in the textConverted text field. Any help would be greatly appreciated.

    Thanks,
    JOD8FY
     
  2. macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #2
    I think your problem is that repalceAll() expects a regular expression.
    You need something like:-

    replaceAll("\\?", "0");

    In a regular expression ? acts as a quantifier. To specify the character '?' you need to escape it, ie '\?', but to stop Java from interpretting the '\' as an escape sequence you need to escape the '\'… hence '\\?'.

    Hope this makes sense!

    b e n
     
  3. thread starter macrumors 6502a

    JOD8FY

    Joined:
    Mar 22, 2004
    Location:
    United States

Share This Page