1

我有这样的代码尝试捕捉

package example; 

import java.util.InputMismatchException; 
import java.util.Scanner; 

public class Example { 

public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    int rep; 
    int[] arraya = new int[2]; 
    do { 
     try { 
      rep = 0; 
      System.out.print("input col :"); 
      int kol = input.nextInt(); 
      System.out.print("input value :"); 
      int val = input.nextInt(); 
      arraya[kol] = val; 
     } catch (InputMismatchException e) { 
      System.out.println("input must integer"); 
      rep = 1; 
      input.next(); 
     } catch (ArrayIndexOutOfBoundsException e) { 
      System.out.println("out of range"); 
      rep = 1; 
     } 
    } while (rep == 1); 
} 
} 

为什么一定要我在catch(InputMismatchException e);添加input.next();避免无限循环?

为什么catch(ArrayIndexOutOfBoundsException e);不需要input.next();以避免无限循环?

catch(ArrayIndexOutOfBoundsException e);,循环运行良好没有input.next();为什么它不同于catch(InputMismatchException e);

+0

您不应该捕获'ArrayIndexOutOfBoundsException'。你应该修复导致它的错误。 – EJP

+0

@EJP感谢您的回复,我让代码知道'ArrayIndexOutOfBoundsException'和'InputMismatchException'为什么他们在循环中处理不同之间有什么不同 – fikriarroisi

回答

1

因为如果你输入一个非整数的性格,int kol = input.nextInt();等待用户再次输入int,它会继续尝试读,因为它没有被消耗掉以前输入的字符。

如果输入了界外int,它被消耗掉,而下int在下一次迭代读取。

+1

@Tom我编辑了我的答案,谢谢。 – Maroun

+0

感谢您的回答 – fikriarroisi