Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

JOD8FY

macrumors 6502a
Original poster
Mar 22, 2004
633
0
United States
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
 

lazydog

macrumors 6502a
Sep 3, 2005
709
6
Cramlington, UK
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
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.