java util扫描仪输入验证

java util扫描仪输入验证,java,validation,java.util.scanner,Java,Validation,Java.util.scanner,我想对我的输入进行验证,无论它是字符串还是带有syso消息的双精度输入,在适当的地方打印“您的输入必须是字符串/双精度整数” //scanner name weight height Scanner userInputScanner = new Scanner(System.in); System.out.print("Name your pet: "); String newName = userInputScanner.nextLine(); KungFuPanda.setName(newN

我想对我的输入进行验证,无论它是字符串还是带有syso消息的双精度输入,在适当的地方打印“您的输入必须是字符串/双精度整数”

//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.");

有人能修改我的代码并向我解释更改吗

为什么不使用检查下一个请求输入的方法呢

 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 -
 }

如果您的一个输入失败,请确保您只在一切正常时创建宠物。

当我使用此代码时,最底层的print语句需要一个局部变量newWeight。当前的newWeight来自一个抽象类,其中声明了set和get方法。我怎样才能解决这个问题?