英文:
Doesn't take input inside finally block
问题
以下是代码部分的中文翻译:
public static void main(String[] args) {
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("无效输入");
} finally {
System.out.println("是否要重复(y/n)");
c = s.next().charAt(0);
}
} while (c == 'y' || c == 'Y');
}
关于您提到的问题,当您提供有效输入时,在排序后它也会在finally
块内接受输入字符c
。但当您提供无效输入时,进入catch
块后,程序不会执行finally
块中的输入操作,因为异常已经终止了程序的正常流程。这就是为什么在这种情况下不会接受输入字符c
的原因。
英文:
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');
}
When I am giving valid input then after performing sorting it also takes input character c inside finally block, but when i give invalid input then after going to catch block it only prints the output inside finally block but doesn't take input character c. Why is it happening so?
答案1
得分: 4
可能是因为您的扫描器在接收无效输入后未能前进。根据Scanner的官方文档:
public int nextInt(int radix)
以int形式扫描输入的下一个标记。如果下一个标记无法转换为有效的int值,将引发InputMismatchException,如下所述。
如果翻译成功,扫描器将前进到匹配的输入。
还有:
当扫描器引发InputMismatchException时,扫描器将不会传递引发异常的标记,以便可以通过其他方法检索或跳过它。
因此,您的扫描器永远不会超越nextInt
,并且不会执行next()
。
英文:
Probably this happens because your scanner does not advance after receiving invalid input.
According to 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.
And also:
> 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.
Therefore your scanner will never go past nextInt
and reach the execution of next()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论