我想对我的输入进行验证,无论是字符串还是带有syso消息的double,它都会输出"你的输入必须是字符串/双整数"在适当情况下。
//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.");
有人可以修改我的代码并向我解释这些变化吗?
答案 0 :(得分:0)
为什么不使用检查下一个请求输入的方法?
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 -
}
如果您的某个输入失败,请确保只在一切正确的情况下创建您的宠物。