Question
The code has a flaw that we want to fix. The text file we are reading is supposed to be filled with integers, one integer
The code has a flaw that we want to fix. The text file we are reading is supposed to be filled with integers, one integer per line. If one of the lines contains a corrupted piece of data (not an integer), the MultiCatch program stops, reports an error and exits. Change the flow of control in the sample code in such a way that a corrupted line (or multiple lines) of text file does not prevent the program to continue printing out the rest of the numbers from the file.
public class MultiCatch {
public static void main(String[] args) {
int number; // To hold a number from the file try
{
// Open the file.
File file = new File("Numbers.txt");
Scanner inputFile = new Scanner(file);
// Process the contents of the file.
while (inputFile.hasNext())
{ // Get a number from the file.
number = inputFile.nextInt();
// Display the number.
System.out.println(number);
} // Close the file.
inputFile.close();
}
catch(FileNotFoundException | InputMismatchException ex)
{
// Display an error message.
System.out.println("Error processing the file.");
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started