2014-04-01 108 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