[英]Java reprompt for user input with try… catch
因此,如果用戶輸入像453- *這樣的后綴值,我的方法EvalPostFix()可以完成工作,但是當用戶輸入無效的東西(如43 * +)或任何無效字符串時,希望程序重新輸入用戶輸入不知道如何用try catch實現..
“
String in;
while(true){
System.out.println("Please enter the numbers first followed by the operators, make sure to have one less operator than of numbers");
try {
in = getString();
int result = EvalPostFix(in);
System.out.println(result);
} catch (IOException e) {
// TODO Auto-generated catch block
String s = "Not a valid postfix string";
e.toString();
in = getString();
}
}
“
看看你的代碼,我認為你只需要擺脫in = getString();
在catch
塊中,在try塊的末尾添加一個break
。
我不建議使用while(true)
或IOException
來處理你正在做的事情,但這應該讓你的代碼正常工作。
使用標志:
boolean flag = false;
while(!flag)
{
//make the loop break, if no exception caught
flag = true;
try{
}
catch{
//make the loop repeat
flag = false;
}
}
這應該在每次捕獲異常時重復提示。 您也可以使用它來驗證輸入。
旗幟的定位取決於您的偏好。 我想在發生錯誤時標記為true;)
一旦獲得有效輸入,這也會打破你的while循環。
這樣的東西可用於獲得所需規格的輸入
public static void userMove() {
System.out.println("Where would you like to move? (R, L, U, D)\n");
Scanner input = new Scanner(System.in) ;
while (true){
String userInput = input.next() ;
if(userInput.length()>1){
System.out.println("Please input a valid direction");
}else{
break ;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.