有没有一种方法可以通过异常处理重复消息,直到输入正确?

g0czyy6m  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(273)

我正在做一个项目,并制作了一个read方法来读取用户的输入,但是,如果他们没有输入正确类型的值,我想返回一个print语句,并不断重复这个过程,直到他们输入正确为止。这是到目前为止的代码,但它似乎没有打印我的打印语句。

package Project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Read
{
  // Will return user input with exception handling.
   public static String read(String label)
   {
      boolean success = false;
      System.out.println( "\nProvide your " + label + ":" );
      System.out.print( "> " );

      BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

      String value = null;

      while (!success) {
         try {
            value = input.readLine();
            success = true;
         } catch (IOException ex) {
            System.out.println("Sorry that was an invalid input. Try again.");
            ex.printStackTrace();
         }
      }

      return value;
   }//Read Method.
}//Class.
gmol1639

gmol16391#

你需要循环,只要 value 是无效的,所以对你来说 value == null || value.isEmpty() . 所以请提示( > )也在循环中。
我会把错误处理从循环中去掉,因为这不是您可以恢复的东西。这与使用输入无关,但更多的是系统故障,即程序无法读取输入流。所以只要说发生了一个错误就结束了。

public static String read(String label) {
    String value = "";

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    System.out.println( "\nProvide your " + label + ":" );

    try {

        while (value == null || value.isEmpty()) {
            System.out.print( "> " );
            value = input.readLine();

            if(value.isEmpty()) {
                System.out.println("Sorry that was an invalid input. Try again.");
            }
        }

    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }

    return value;
}//Read Method.

相关问题