Shahrokh Aryana Shahrokh Aryana - 6 months ago 16
Java Question

How to check if a double value contains special characters

I was writing a code for a program in which the user enters 2 to 4 numbers which can be up to 2 decimal places long. However before the user enters these numbers they must enter the pound symbol, e.g. #12.34. I was wondering how i would check if the double value entered began with the pound sign, and if the user forgot to input it, to re-prompt them to do it again. So far im using a String value and the '.startsWith()' code, but I'm finding later on that a String value is making the rest of the program impossible to code, so i was wanting to keep it a double value. This is the code I have at the moment but wish to change to a double:

String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
System.out.print("Re-enter the 4 numbers with a pound key: ");
input = keyboard.next();
}


I was wanting to replace the String with double as mentioned previously.

Answer
String input;
System.out.print("Enter the 4 numbers with a pound key: ");
input = keyboard.next();
while (!input.startsWith("#")) {
 System.out.print("Re-enter the 4 numbers with a pound key: ");
 input = keyboard.next();
}
// if your excution reaches here. then it means the values entered by user is starting from '#'.
String temp = input;
double value = Double.parseDouble(temp.replace("#",""));

For the rest of the program use value. I think the coding should be possible now.