不在 finally 块中接受输入
Doesn't take input inside finally block
public static void main(String[] args) {
// TODO Auto-generated method stub
char c;
do {
Scanner s=new Scanner(System.in);
try {
int size=s.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++) {
arr[i]=s.nextInt();
}
bubblesort(arr);
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
} catch(Exception e) {
System.out.println("Invalid Input");
} finally {
System.out.println("Want to repeat(y/n)");
System.out.println(s);
c=s.next().charAt(0);
}
} while(c=='y' || c=='Y');
}
当我给出有效输入然后在执行排序后它也在 finally 块中接受输入字符 c,但是当我给出无效输入然后在去 catch 块之后它只打印 finally 块中的输出但不接受输入字符 C.为什么会这样?
发生这种情况的原因可能是您的扫描仪在收到无效输入后没有前进。
根据official documentation of Scanner:
public int nextInt(int radix)
Scans the next token of the input as an int. This method will throw InputMismatchException if the next
token cannot be translated into a valid int value as described below.
If the translation is successful, the scanner advances past the input
that matched.
还有:
When a scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
因此您的扫描器永远不会超过 nextInt
并到达 next()
的执行
public static void main(String[] args) {
// TODO Auto-generated method stub
char c;
do {
Scanner s=new Scanner(System.in);
try {
int size=s.nextInt();
int[] arr=new int[size];
for(int i=0;i<size;i++) {
arr[i]=s.nextInt();
}
bubblesort(arr);
for(int i=0;i<arr.length;i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
} catch(Exception e) {
System.out.println("Invalid Input");
} finally {
System.out.println("Want to repeat(y/n)");
System.out.println(s);
c=s.next().charAt(0);
}
} while(c=='y' || c=='Y');
}
当我给出有效输入然后在执行排序后它也在 finally 块中接受输入字符 c,但是当我给出无效输入然后在去 catch 块之后它只打印 finally 块中的输出但不接受输入字符 C.为什么会这样?
发生这种情况的原因可能是您的扫描仪在收到无效输入后没有前进。 根据official documentation of Scanner:
public int nextInt(int radix)
Scans the next token of the input as an int. This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched.
还有:
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
因此您的扫描器永远不会超过 nextInt
并到达 next()