简体   繁体   中英

java util-scanner input validation

I'd like to make validation to my input, whether it is a string or a double with a syso message, which prints "your input must be a String/double integer" where appropriate.

//scanner name weight height
Scanner userInputScanner = new Scanner(System.in);
System.out.print("Name your pet: ");
String newName = userInputScanner.nextLine();
KungFuPanda.setName(newName);
System.out.println("Pet weight (lbs): ");
double  newWeight= userInputScanner.nextDouble();
KungFuPanda.setWeight(newWeight);
System.out.println("Pet height (cm): ");
double  newHeight = userInputScanner.nextDouble();
KungFuPanda.setHeight(newHeight);

System.out.println("Name of our pet you have created is " + newName + ", it's weight     is " + newWeight + "lbs and it's height is "
            + newHeight + "cm.");

Can someone amend my code and explain to me the changes?

Why don't you just use the methods which check for next requested input?

 double newWeight;

 if(userInputScanner.hasNextDouble()) { 
      System.out.println("Pet weight (lbs): ");   
      newWeight= userInputScanner.nextDouble();
      KungFuPanda.setWeight(newWeight);
 } else {
      System.out.println("your input must be a String/double integer");
 }

 ... ... ...

 if(newWeight!=null) {
      System.out.println("Weight of our pet you have created is " + newWeight "+lbs.");
 } else {
   - error outprint -
 }

In case, one of your inputs fails, make sure that you only create your pet when all is correct.

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