Skip to content
Advertisement

Converting a string with a leading special character into a double?

I’m at the beginning of my Java journey, and have run into a little problem that I’m having a little difficulty figuring out.

JavaScript

I am looking to be able to convert the string input into a double even if it contains a leading “$” character. I am currently running into a NumberFormatException.

Unsure of how to utilize try, catch, and finally statements (if they’re at all applicable here).

Thanks in advance!

Advertisement

Answer

Java’s String class offers many methods for manipulating strings. One such method is the replace() method, which allows you to replace all instances of one string with another. This method takes 2 arguments, the target string and the replacement string. You can remove the target string by simply passing an empty string for the replacement string. For example:

JavaScript

Would produce:

JavaScript

Using this, we can update your code by adding only one method call:

JavaScript

Please note that CostPerEmployee and CostPerEmployeeD are not defined in the code block you provided, and you have not handled the IOException thrown by the readLine() method. I am assuming that this code block is from a larger program, where these problems are resolved. In the future, a minimal, reproducible example can help clear these things up.

Advertisement