Hi, I might have spotted an error in one of the mock exams on the Wiley testbanks.
For the following question:
Assuming zoo.csv is a multiline text file, what is true of the following code snippet?
A. It prints the first line of the file to the console.
B. It prints the entire contents of the file.
C. The code does not compile.Your selection is incorrect
D. The code does compile, but the reader is not closed.
E. The code may print null at runtime.Your selection is incorrect
F. The code compiles but may throw a NullPointerException at runtime.
We get this as solution:
This code compiles, so C is incorrect. It uses a try-with-resource block to open the FileReader and BufferedReader objects. Therefore, both get closed automatically and D is incorrect. At first glance, the code appears to print every line of the file, but it contains a bug. The readLine() method is called twice on every iteration of the loop, so the code actually skips the first line and outputs every other line after that, so A and B are incorrect. Since System.out.println() is capable of printing null values, a NullPointerException will not be thrown, so F is incorrect. The correct answer is E, since the loop will output an extra null text value on files with an odd number of lines.
I've copied the code to my IDE and it wont compile. I found a similar issue and they recommended compliing using the terminal, but there it also gives me compile errors regarding the not handeling of the Exceptions that instantiating and closing the resources can produce.
Am I missing something or is this really an error in the material?
I can't help you yet with the correct resolution of the question, but there are plenty of experienced people here who can. But if you want to consult the known typos or mistakes that have already been reported by other users of the book you can go to www.selikoff.net to see the list for each book.
when you copied the code into your IDE, did you also add a catch or finally clause? A try statement can never be on its own.
The book probably made some remark somewhere that those missing things are assumed to be present.
I hate signatures!
Ken De Becker
posted 11 months ago
I did not initially, if I do add the catch clause, it does compile and the answers is correct.
I did find the remark that for code snippets, the surrounding code is implied, so I'll have to be carefull of this and "imagine" the code being there.
Thanks for pointing this out.
Piet is correct that the exam includes code snippets. You get to imagine the method and class when that happens. (This happens frequently on the exam as well to save space. After all, you can only fit so much code on the screen)