2

I want to check if the input I entered is the correct data type. For example if the user enters an int when I want them to enter a double then the program tells them there is an error. This is what I have so far:

System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
try
{
    Double temperature = Double.parseDouble(temp);
}
catch(Exception e)
{
    isValid = false;
    System.out.println("Temperature  must be a double ");
}

All its doing is continuing on through the program and not printing out the error message when I enter an int. Been stuck on this for a while so any help would be appreciated.

2
  • Every int is a valid double, so why would you expect it to fail? Commented Feb 15, 2019 at 16:37
  • 2
    An int is also a double! You have to explicitely test against intness, too. Commented Feb 15, 2019 at 16:38

2 Answers 2

1

I think you are looking to validate only decimal numbers (not including integers). If that is the case then you can use a regex for the same :

System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
while (temp != null && !temp.matches("^[0-9]*\\.([0-9]+)+$")) {       // use of regex here
    System.out.println("Enter the temperature in double:");
    temp = input.nextLine();                                          // read input again
}

This will loop until the user gives in only a valid decimal input. Explanation of this regex.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you don't want int to get accepted, you can just add an if to check whether the input String has a decimal point or not.

    System.out.println("Enter the temperature in double:");
    String temp = (new Scanner(System.in)).next();
    if (temp.contains(".")) {
        try {
            Double temperature = Double.parseDouble(temp);
        } catch(Exception e) {
            isValid = false;
            System.out.println("Temperature  must be a double ");
        }
    } else {
        isValid = false;
        System.out.println("Temperature  must be a double ");
    }

1 Comment

Just retaining the original try catch should deal with that problem, edited!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.