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.