Reputation: 23
I wrote some code for my assignment, 'heap sort'.
I received input file name.
Scanner in = new Scanner(System.in);
System.out.print("insert 'input file name' : ");
String fileName = in.nextLine();
in.close();
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();
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.
Upvotes: 2
Views: 71
Reputation: 37835
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.
Upvotes: 3