0

I used scanner for the first time. I got an error @ finish, saying that finish is not closed properly. What is meant by that. Thanks!

import java.util.Scanner;

public class inputvalue {
    public static void main(String[] args) {
        int i = 0;
        Scanner finish = new Scanner(System.in);
        int j = finish.nextInt();
        while (i < j) {
            System.out.print("hai");
            i = i + 1;
        }

    }
}
Johny
  • 2,128
  • 3
  • 20
  • 33
aishwaryat
  • 103
  • 1
  • 4
  • First off horrible code formatting. And also.... `finish.close();` I don't think you are getting an error but you are simply getting a warning?. When you don't close a resource stream like a `Scanner`/`InputStream`/`etc...` you will get a `resource leak` – 3kings Mar 20 '16 at 06:31
  • add `finish.close()` to avoid resource leak – Johny Mar 20 '16 at 06:33

2 Answers2

0

The compilator warns you about a potential leak of memory. You have two solutions when encountering this problem.

and latter

Use a try-with-resources block that will automatically close your stream. That'll prevent your program from having a leak in its resources.

int i = 0, j;
try(Scanner finish = new Scanner(System.in)){
    j = finish.nextInt();
}
while (i < j) {
    System.out.print("hai");
    i = i + 1;
}

and earlier

Use a try-finally and within the latter check if your object is null. If it's not, close it manually.

int i = 0, j;
Scanner finish = new Scanner(System.in);
try {
    j = finish.nextInt();
} finally {
    if (finish != null) {
        finish.close();
    }
}
while (i < j) {
    System.out.print("hai");
    i = i + 1;
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
-1

Scanner implements Closeable interface which has a close method. All the classes implementing this interface represent that they are using resources that needs to be closed. You should therefore clsoe Scanner. One way of doing this is in the predestroy method as:

@PreDestroy
public void preDestroy {
    scanner.close();
}

The other way would be to close scanner at the end of your code as:

public static void main(String[] args) {
    int i = 0;
    Scanner finish = new Scanner(System.in);
    int j = finish.nextInt();
    finish.close();
    while (i < j) {
        System.out.print("hai");
        i = i + 1;
    }
}

Read more about Closeable here and here

Community
  • 1
  • 1
Prashant
  • 4,775
  • 3
  • 28
  • 47
  • 1
    Actually, the proper method is to use try-with-resources – Jim Garrison Mar 20 '16 at 06:41
  • Yes of course! I was just attempting to show the use case – Prashant Mar 20 '16 at 06:42
  • A class consisting entirely of a `main()` is hardly a candidate for an `@PreDestroy` method, and unless `scanner` is rather pointlessly made into a static member of the class your suggestion won't even compile. – user207421 Mar 20 '16 at 07:41