Question: Part1: Exception. A heart rate data file HR.txt , which records hundreds of heart rate readings (in integer), is contaminated (by viruses) and many illegal
Part1: Exception. A heart rate data file ""HR.txt" , which records hundreds of heart rate readings (in integer), is contaminated (by viruses) and many illegal data (unknown data type) are inserted. Write a program "HeartRate.java" to read the data file and output the number of good readings as well as the number of bad data. The definition is described as follows: Good data: any positive integer reading. Bad data: (1) Any non-integer reading; (2) Any negative (integer) reading. In your program, you need two exceptions to handle two kinds of bad data.
For the non-integer reading, you can use nextInt() method to read an integer from the file, if the data is not an integer, InputMismatchException will be thrown. Your program must catch this exception.
To handle the negative reading, you may want to declare your own Exception class: HRIllegalValueException (you are expected to write HRIllegalValueException.java that contains the class), and threw this exception when a negative value is read.
Note: your program should not terminate when a bad data is read. Therefore, you must use try/catch block to handle the bad data. Your program is expected to print out (on the screen) the number of good HR readings and the number of bad data.
A sample execution trace:
$ java HeartRate HRIllegaValueException: cannot be negative. HRIllegaValueException: cannot be negative. Good Data: 24 Bad Data: 6
Requirements:
Files to be submitted: HeartRate.java, HRIllegalValueException.java, and HR.txt.
The main method of HeartRate class should look like:
public static void main(String[] args) throws IOException { } You can use FileReader and Scanner to handle the data input from a file.
Scanner input = new Scanner(new FileReader("HR.txt")); The file "HR.txt" must be at the same directory of our source code.
The nextInt() method will throw out an InputMismatchException if the read data is not int type. You may assume all good readings are int type, and the bad data are other types. A try/catch block should be good enough to handle this problem. Yes, you really want to catch InputMismatchException in your catch block.
When a non-ingeter is read by nextInt() method, an InputMismatachException is thrown. The bad data (a non-integer), however, has not been consumed yet, it is your responsibility to consume this data so that the next data can be read. Otherwise, your program will be always stuck at the bad data and cause an infinite loop.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
