使用try / catch时如何避免无限循环?

时间:2017-11-07 07:11:29

标签: java try-catch

我有这段代码

public void askUserForStrategy(){

    try{

        System.out.println("What strategy do you want to use?\n");
        System.out.println("1 = Math.random\t     2 = System time\t "
        + "3 = Sum of Math.random and System time");

        int strategy = sc.nextInt();

        selectStrategy(strategy);

    }

    catch(InputMismatchException Exception){

        System.out.println("That is not an integer. Try again.\n");
        askUserForStrategy();

    }

}

我想要它做的基本上是要求用户键入一个整数,如果用户键入了一个String,例如,捕获该异常并再次启动该方法(要求用户键入一个整数值)。但是当用户键入String时,该方法会循环。

4 个答案:

答案 0 :(得分:2)

nextInt()抛出异常时,Scanner对象会在下次调用时尝试使用相同的字符串。

尝试在Scanner内分配新的try对象。或者尝试在nextLine()内拨打catch,这样您就会弃掉非法行。

请注意,这种方法并不好,因为在非常多的非法输入(很多,但理想情况下是无限次尝试)之后会发生堆栈溢出。

我建议您在do-while正文末尾使用returntry

答案 1 :(得分:1)

试试这个:

public void askUserForStrategy() {

 for(int i=0; i<1; ++i) {
  try{

    System.out.println("What strategy do you want to use?\n");
    System.out.println("1 = Math.random\t     2 = System time\t "
    + "3 = Sum of Math.random and System time");

    int strategy = sc.nextInt();

    selectStrategy(strategy);
    break;  //break loop when there is no error
  }

  catch(InputMismatchException Exception){

    System.out.println("That is not an integer. Try again.\n");
    //askUserForStrategy();
    continue; //for clarity

  }
 }
}

答案 2 :(得分:1)

也许你正在寻找类似的东西

public void askUserForStrategy(){
Boolean loopFlag = true;
while(loopFlag) {
try{

    System.out.println("What strategy do you want to use?\n");
    System.out.println("1 = Math.random\t     2 = System time\t "
    + "3 = Sum of Math.random and System time");

    int strategy = sc.nextInt();
    Integer.parseInt(strategy);
    loopFlag  = false;
    selectStrategy(strategy);
}

catch(Exception e){

    //Parse has failed due to wrong input value, But loop will continue

}}}

答案 3 :(得分:0)

这可能是你在寻找..

public void askUserForStrategy() {
        while (true) {
            try {
                Scanner sc = new Scanner(System.in);
                System.out.println("What strategy do you want to use?\n");
                System.out.println("1 = Math.random\t     2 = System time\t " + "3 = Sum of Math.random and System time");

                int strategy = sc.nextInt();
                System.out.println("Selected strategy : " +strategy);
                break;
            } catch (Exception e) {
                System.out.println("That is not an integer. Try again.\n");
                continue;
            }
        }
        // selectStrategy(strategy);
    }

如果用户选择了String,那么它将再次询问选项..

如果用户选择Integer,那么它将采用用户选择的策略选项并继续程序流程。(意味着在break的帮助下退出while循环,然后调用selectStrategy方法)

由于