# Thread: Check if double is double

1. Member
Join Date
Sep 2009
Posts
5
Rep Power
0

## Check if double is double

How do i check to see if the user entered a valid double, and if wrong tells them to try again??

2. Senior Member
Join Date
Aug 2009
Posts
2,388
Rep Power
14
You could try converting the value to a double using Double.parseDouble. If the conversion fails then it's not a double.

3. Member
Join Date
Sep 2009
Posts
5
Rep Power
0
How would i do that i have never used that, an example would be great thx.

4. Are you reading the input from the keyboard, a file, or what?

If you just want to check if a String is a valid double, try parsing it. If it parses, yeah! If not, an exception is thrown, catch it, and return false.

Java Code:
```public class Test
{
/**
* Main function
*
* @param args
*            (not used)
*/
public static void main(String[] args)
{
String input = "1.7e-6";
double myDouble = Double.parseDouble(input);

System.out.println(myDouble);

// throws a NumberFormatException
double invalidDouble = Double.parseDouble("INVALID!");

System.out.println(invalidDouble);
}
}```

5. Member
Join Date
Sep 2009
Posts
5
Rep Power
0
I'm reading in numbers like 4 and 89.78 and dont want "hi" or "seventy"

6. Senior Member
Join Date
Aug 2009
Posts
2,388
Rep Power
14
Originally Posted by marshalthrone
How would i do that i have never used that, an example would be great thx.

7. Member
Join Date
Sep 2009
Posts
5
Rep Power
0
public class Sort3 {

public static Scanner in = new Scanner (System.in);

public static void main (String [] args) {

double a = GetDouble();

double b = GetDouble();

double c = GetDouble();

}
public static double GetDouble() {

System.out.print ("Enter a double: ");

double x = in.nextDouble ();

return x;
}
}

Heres my code i want to check if the double entered is a number like 4 and 78.34, not "seventy two" or "what"

8. Senior Member
Join Date
Aug 2009
Posts
2,388
Rep Power
14

9. Check out the API for the Scanner class. There's a method that does exactly what you need.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•