簡體   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