2

I wrote some code for my assignment, 'heap sort'.

  1. I received input file name.

    Scanner in = new Scanner(System.in);
    System.out.print("insert 'input file name' : ");
    String fileName = in.nextLine();
    in.close();
    
  2. Then I read that file.

    in = new Scanner(new File(fileName));
    ArrayList<Integer> source = new ArrayList<Integer>();
    MyIntHeap heap = new MyIntHeap();
    for(int idx=0; in.hasNextInt(); ++idx){
        source.add(in.nextInt());
        heap.add(source.get(idx));
    }
    in.close();
    
  3. Finally, I tried to receive output file name...

    in = new Scanner(System.in);
    System.out.print("insert 'output file name' : ");
    fileName = in.nextLine();
    in.close();
    

At this point, program threw an error to me.

insert 'input file name' : abc.txt
insert 'output file name' : Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at Solution.main(Solution.java:13)

For now I solve problem as

    Scanner in = new Scanner(System.in);
    System.out.print("insert 'input file name' : ");
    String inputFile = in.nextLine();
    System.out.print("insert 'output file name' : ");
    String outputFile = in.nextLine();
    in.close();

But I'd like to know why the problem happened.

Donggi Kim
  • 23
  • 4

1 Answers1

3
Scanner in = new Scanner(System.in);
...
in.close();

The problem here is that you are closing a Scanner which is reading System.in. This also closes System.in.

The solution is that you should just not close the Scanner.

You should always close resources that you've created. System.in isn't a resource you've created, so you don't need to close it.

Radiodef
  • 35,285
  • 14
  • 78
  • 114
  • Thank you. I thought that I should close when I use Scanner, because eclipse says "Resource leak: 'in' is never closed" when I didn't write that. Then, 2. in = new Scanner(new File(fileName)); ─ in this case, is it right to close Scanner? – Donggi Kim Apr 10 '16 at 05:02
  • Yes, you should close the Scanner that's reading from a file. IDE warnings aren't perfect so very occasionally you can ignore them. `new Scanner(System.in)` is just one of those rare cases where you should ignore the warning. – Radiodef Apr 10 '16 at 15:08