繁体   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]+"=");
        }

    }
}

以上是代码,我总是收到以下错误:

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

如您所见,我尝试关闭扫描仪,但问题仍然存在。也许我做错了什么。

关闭那个Scanner时要非常小心,因为那也会关闭System.in 在这种情况下,您使用的工具已确定至少有一个代码路径无法关闭Scanner 在这种情况下, Scanner.nextInt()可能会throw InputMismatchExceptionNoSuchElementExceptionIllegalStateException中的任何一个(或者您可能会超出数组边界,static 分析很棘手)。

确定您仍然关闭Scanner方法是finally块。 喜欢,

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]+"=");
}

更好的方法称为try-with-Resources Statement 喜欢,

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