简体   繁体   English

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

[英]Java reprompt for user input with try… catch

So if a user puts in a postfix value like say 453-* , my method EvalPostFix() does the work, but when the user inputs something invalid like 43*+ or any invalid string want the program to repromt the user for input dont know how to implement 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();
        }
    }

'

Looking at your code I think you just need to get rid of the in = getString(); 看看你的代码,我认为你只需要摆脱in = getString(); in the catch block and add an break at the end of the try block. catch块中,在try块的末尾添加一个break

I don't recommend using a while(true) or an IOException for what you are doing though, but that should get your code working. 我不建议使用while(true)IOException来处理你正在做的事情,但这应该让你的代码正常工作。

Use a flag: 使用标志:

boolean flag = false;
while(!flag)
{
//make the loop break, if no exception caught
flag = true;
    try{

    }
    catch{
       //make the loop repeat
       flag = false;
    }
 }

this should repeat the prompt every time you catch an exception. 这应该在每次捕获异常时重复提示。 you can also use this to validate input. 您也可以使用它来验证输入。

how the flag is oriented depends on your preference. 旗帜的定位取决于您的偏好。 I like to flag true when an error occured ;) 我想在发生错误时标记为true;)

this will also break your while loop, as soon as you get a valid input. 一旦获得有效输入,这也会打破你的while循环。

Something like this is can be used to get an input of desired specifications 这样的东西可用于获得所需规格的输入

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