2014-04-01 83 views
0

我想对我的输入进行验证,无论是字符串还是带有syso消息的double,在适当的位置打印“您的输入必须是字符串/双精度整数”。java util-scanner输入验证

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

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

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

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

+0

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