0
Follow
0
View

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);
        System.out.print("请输入数组元素的个数:");
        int len = sc.nextInt();
        double[] a = new double[len];
        double min = 0;

        System.out.print("请输入数组元素:");
        for (int i = 0; i < len; i++) {
            a[i] = sc.nextDouble();
            if (i == 0 || a[i] < min) {
                min = a[i];
            }
        }

        sc.close();

        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

使用UserAuthenticator()的蒸汽承载身份验证在401未授权时总是失败

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

Xcode日志“写入分析变量”

verilog Mars中Code是什么意思

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

使用Slither时超过了最大递归深度

Xcode构建失败:请求但没有找到扩展点

vscode运行c语言程序出现如下错误

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