简体   繁体   中英

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 . In this case, the tool you are using has decided there is at least one code path where you fail to close the 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).

The old way to be certain that you still closed the Scanner was a finally block. 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 . 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]+"=");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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