The posted code does the following:
- Read all lines, just for counting
- Create an array with the right size
- Read all lines again, this time for storing
- Print all lines in reverse order
It's wasteful to read a file completely just to find the number of lines, and then need to read the file again to store the content.
It would be better to store the lines in a data structure that can grow its capacity as needed, to eliminate the need to know the number of lines in advance. That is, use any List
implementation.
Possible bug
The description doesn't mention that there is precisely one integer per line in the input.
It must be the case, otherwise this code may not work well:
for(int i=0; i<buffer.length; i++) {
buffer[i] = Scan.nextInt();
}
That is, if there are multiple numbers per line, then you will not read the entire file,
only the first \$N\$ numbers.
Similarly, if there are empty lines, then there may not be enough numbers,
and then the .nextInt
call will throw a NoSuchElementException
.
The thing is, since there program doesn't use any integer operation,
only read and print,
there's no point reading integers.
Keep in mind that when you read integers,
you also incur a parsing step.
It would make more sense to read the lines as strings,
it would be simpler, and it seems that's all you really need anyway.
Suggested implementation
Here's an alternative, more efficient solution,
that also simplifies the reversing logic using a LinkedList
, with a descendingIterator
:
LinkedList<String> lines = new LinkedList<>();
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());
}
scanner.close();
Iterator<String> iterator = lines.descendingIterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}