0

I am trying to figure out how to validate the input of a user. I want the user to enter a double but if the user enters a string I want the question repeated until a double is entered. Iv'e searched but I couldn't find anything. Below is my code so far any help is appreciated. I have to use a do while loop I am stuck on what to put in the while loop to make sure the input is a double and not a string.

public class FarenheitToCelsius {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

  double fahrenheit, celsius; 
  Scanner in = new Scanner(System.in);
  do{
    System.out.printf("Enter a fahrenheit degree: ");
    fahrenheit = in.nextDouble();
  }
  while();

  celsius = ((fahrenheit - 32)*5)/9;

  System.out.println("Celsius value of Fahrenheit value " + fahrenheit + " is " + celsius);
1
  • You will be unhappy with the results of this code. I'd change those integers to doubles: 32.0, 5.0, 9.0. Integer division surprises a lot of new programmers. Commented Nov 26, 2017 at 14:44

1 Answer 1

1

One trick you can use here is to read the entire user input as a string, which would allow any type of input (string, double, or anything else). Then, use Double#parseDouble() to try to convert that input to a bona-fide double value. Should an exception occur, allow the loop to continue, otherwise, end the loop and continue with the rest of your program.

Scanner in = new Scanner(System.in);
boolean isValid;
do {
    System.out.printf("Enter a fahrenheit degree: ");
    isValid = false;
    String input = in.nextLine();
    try {
        fahrenheit = Double.parseDouble(input);
        isValid = true;
    }
    catch (Exception e) {
         // do something
    }
} while(!isValid);

celsius = ((fahrenheit - 32) * 5) / 9;
Sign up to request clarification or add additional context in comments.

Comments

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.