Question: The while loop makes up to three attempts to read an integer divisible by 4 from input into numTires. Write a catch block to catch

The while loop makes up to three attempts to read an integer divisible by 4 from input into numTires.
Write a catch block to catch any InputMismatchException thrown. In the catch block:
Output "Unexpected input: The TotalTires program exits".
Assign triesLeft with 0.
Then, write another catch block to catch any Exception thrown. In the catch block:
Output the message of the Exception.
Subtract 1 from triesLeft.
End each output with a newline.
Click here for examples
Ex 1: If the input is 136, then the output is:
Tries left: 3 Valid input: 136 tires can make 34 automobiles
Ex 2: If the input is P, then the output is:
Tries left: 3
Unexpected input: The TotalTires program exits
Ex 3: If the input is 74136, then the output is:
Tries left: 3
The number of tires must be divisible by 4
Tries left: 2
Valid input: 136 tires can make 34 automobiles
import java.util.Scanner;
import java.util.InputMismatchException;
public class TotalTires {
public static void main(String[] args){
Scanner scnr = new Scanner(System.in);
int numTires;
int triesLeft =3;
while (triesLeft >0){
System.out.println("Tries left: "+ triesLeft);
try {
numTires = scnr.nextInt();
if (numTires %4!=0){
throw new Exception("The number of tires must be divisible by 4");
}
triesLeft =0;
System.out.print("Valid input: ");
System.out.println(numTires +" tires can make "+(numTires /4)+" automobiles");
}
/* Your code goes here */
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!