简体   繁体   中英

Java User input Validation

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM