Java 尝试循环捕获(InputMismatchException和ArrayIndexOutOfBoundsException之间的差异)
我有这个密码Java 尝试循环捕获(InputMismatchException和ArrayIndexOutOfBoundsException之间的差异),java,arrays,indexoutofboundsexception,inputmismatchexception,Java,Arrays,Indexoutofboundsexception,Inputmismatchexception,我有这个密码 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];
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);
}
}
为什么我必须添加input.next()代码>在捕获中(输入不匹配异常e)代码>以避免无休止的循环
为什么在catch中(arrayindexoutofboundsexceception e)代码>不需要输入。下一步()代码>以避免无休止的循环
在catch中(ArrayIndexOutOfBoundsException e)代码>,循环运行良好,无需输入代码>为什么它不同于捕获(输入不匹配异常e)代码>?因为如果输入非整数字符,int kol=input.nextInt()
不会等待用户再次输入int
,它将继续尝试读取以前输入的字符,因为它没有被使用
如果您输入一个越界int
,它将被消耗,并且在下一次迭代中读取下一个int
您不应该捕捉到阵列索引超出边界异常
。您应该修复导致它的错误。@EJP感谢您的回复,我编写了该代码以了解ArrayIndexOutOfBoundsException
和InputMismatchException
在循环中处理不同的原因