简体   繁体   English

在阵列中使用时如何关闭扫描仪?

[英]How do I close the scanner while using in array?

import java.util.Scanner;

//This is a program to do array functions in java
public class Array {
    public static void line() {
        System.out.println("------------------------------------------------------");
    }
    public static void main(final String[] args) {
        final int[] z = new int[10];// taking array variable
        // taking constant inputs in the z array
        int i;
        Scanner s= new Scanner(System.in);
        System.out.println("Enter The array values");
        for(i=0;i<10;i++){
            z[i]=s.nextInt();
            line();
        }
        s.close();
        line();
        //now printing the array elements
        for(i=0;i<10;i++){
            System.out.println("value of "+z[i]+"=");
        }

    }
}

Above is the code, I am always getting the error given below:以上是代码,我总是收到以下错误:

{
    "message": "Resource leak: 's' is never closed",
    "source": "Java",
    "startLineNumber": 12,
    "startColumn": 17,
    "endLineNumber": 12,
    "endColumn": 18
}

I tried closing the scanner as you can see but the problem still persist.Maybe I am doing somewhere wrong.如您所见,我尝试关闭扫描仪,但问题仍然存在。也许我做错了什么。

Be very wary closing that Scanner , because that will also close System.in .关闭那个Scanner时要非常小心,因为那也会关闭System.in In this case, the tool you are using has decided there is at least one code path where you fail to close the Scanner .在这种情况下,您使用的工具已确定至少有一个代码路径无法关闭Scanner In this case, Scanner.nextInt() might throw any of InputMismatchException , NoSuchElementException or IllegalStateException (or you might exceed the array bounds, static analysis is tricky).在这种情况下, Scanner.nextInt()可能会throw InputMismatchExceptionNoSuchElementExceptionIllegalStateException中的任何一个(或者您可能会超出数组边界,static 分析很棘手)。

The old way to be certain that you still closed the Scanner was a finally block.确定您仍然关闭Scanner方法是finally块。 Like,喜欢,

Scanner s = null;
try {
    s = new Scanner(System.in);
    System.out.println("Enter The array values");
    for(i=0;i<10;i++){
        z[i]=s.nextInt(); // <-- could throw any of the 3 exceptions.
        line();
    }
} finally {
    s.close();
}
line();
//now printing the array elements
for(i=0;i<10;i++){
    System.out.println("value of "+z[i]+"=");
}

But the better newer way is called a try-with-Resources Statement .更好的方法称为try-with-Resources Statement Like,喜欢,

try (Scanner s = new Scanner(System.in)) {
    System.out.println("Enter The array values");
    for(i=0;i<10;i++){
        z[i]=s.nextInt();
        line();
    }
}
line();
//now printing the array elements
for(i=0;i<10;i++){
    System.out.println("value of "+z[i]+"=");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM