Why does the code abnormally show scanner off

crystal_321 注册会员
2023-02-26 14:06

This answer quotes ChatGPT

The reason this code shows the scanner closed abnormally is that the sc.close() method should not be called until the end of the for loop. In the current code, sc.close() is called inside the loop, so the scanner is closed on the first input, preventing subsequent input operations.

Here is the code that has been fixed and should work fine:

import java.util.Scanner;

public class ShiXun1 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int len = sc.nextInt();
        double[] a = new double[len];
        double min = 0;

        for (int i = 0; i < len; i++) {
            a[i] = sc.nextDouble();
            if (i == 0 || a[i] < min) {
                min = a[i];


        System.out.printf("数组中最小元素值为:%f, 其在数组中的下标是:%d", min, findIndex(a, min));

    private static int findIndex(double[] a, double value) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == value) {
                return i;
        return -1;

In the process of fixing the code, another problem was discovered: the placeholders %d,m,loc in System.out.printf were incorrect, and the variable findIndex(a, min) should be used to get the index location of the minimum value. At the same time, for better readability and maintainability, you can encapsulate the finding of the minimum in a separate method, findIndex.

About the Author

Question Info

Publish Time
2023-02-26 14:06
Update Time
2023-02-26 14:06

Related Question

出现报错the condition has length #62 1


R error in geom(line): Aesthetics must be length 1 or same as the data(2296


verilog Mars中Code是什么意思

How to retrieve the host name by IP with dnsjava library?




如何在VS Code web应用程序中保持端口自动打开以进行测试?