简体   繁体   中英

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

'

        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 the catch block and add an break at the end of the try block.

I don't recommend using a while(true) or an IOException for what you are doing though, but that should get your code working.

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 ;)

this will also break your while loop, as soon as you get a valid input.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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