繁体   English   中英

Java使用try ... catch重新启动用户输入

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM