Skip to content

Latest commit

 

History

History
54 lines (46 loc) · 2.73 KB

5d30.md

File metadata and controls

54 lines (46 loc) · 2.73 KB

Back to questions

5d30: Unreliable buffered reader

Disclaimer: In this question, you are going to sabotage the behaviour of class BufferedReader by extending it with an unreliable subclass. The purpose of this is to provide more practice working with exceptions in Java. Clearly you should never do something like this in practice!

Write a class UnreliableBufferedReader which extends BufferedReader from the java.io package. An UnreliableBufferedReader should have two fields: probabilityOfError, of type double, and a random number generator field of type Random.

The constructor of UnreliableBufferedReader should accept a double parameter, and should assign the value of this parameter to probabilityOfError if it lies between 0 and 1 (inclusive). Otherwise the parameter should be "clamped" into the range [0,1]: a negative value should result in probabilityOfError being set to 0; a value greater than 1 should result in probabilityOfError being set to 1. The random number generator should also be constructed.

Override the readLine method of BufferedReader. Your overridden version of this method should invoke the superclass method to read a line, storing a reference to the resulting string in a local variable. Then our method should choose a random double between 0 and 1. If the chosen double is less than probabilityOfError your method should throw an IOException with the message: "Error occurred on input stream". Otherwise, your overriden version of readLine should return the line that was obtained via the superclass call.

Write a demonstration class to illustrate that your unreliable buffered reader is "working" (i.e., not working very well!). Your demonstration program should repeatedly read lines from standard input using an UnreliableBufferedReader, using a probability of your choice. The program should terminate when five lines have been successfully read, at which point you should display the number of calls to readLine that were required.

An example session with your program might look like this:

Attempting to read input from unreliable reader...
Hello
Successfully read input: Hello
Attempting to read input from unreliable reader...
Unreliable
Failed!
Attempting to read input from unreliable reader...
Unreliable
Successfully read input: Unreliable
Attempting to read input from unreliable reader...
Buffered
Failed!
Attempting to read input from unreliable reader...
Buffered
Successfully read input: Buffered
Attempting to read input from unreliable reader...
Reader!
Successfully read input: Reader!
Attempting to read input from unreliable reader...
Signing out.
Successfully read input: Signing out.
Took 7 attempts to read 5 lines from unreliable reader