58.9k views
2 votes
The while loop makes up to three attempts to read an integer divisible by 6 from input into numEggs. Use multiple exception handlers to: Catch an InputMismatchException, output "Unexpected input: The TotalEggs program quits", and assign attemptsLeft with 0. Catch an Exception, output the message of the Exception, and subtract 1 from attemptsLeft. End each output with a newline. Ex: If the input is 72, then the output is: Attempts left: 3 Valid input: 72 eggs = 12 cartons of half a dozen Ex: If the input is J, then the output is: Attempts left: 3 Unexpected input: The TotalEggs program quits Ex: If the input is 45 72, then the output is: Attempts left: 3 The number of eggs must be divisible by 6 Attempts left: 2 Valid input: 72 eggs = 12 cartons of half a dozen

import java.util.Scanner;
import java.util.InputMismatchException;

public class TotalEggs {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int numEggs;
int attemptsLeft = 3;

while (attemptsLeft > 0) {
System.out.println("Attempts left: " + attemptsLeft);

try {
numEggs = scnr.nextInt();

if (numEggs % 6 != 0) {
throw new Exception("The number of eggs must be divisible by 6");
}

attemptsLeft = 0;
System.out.print("Valid input: ");
System.out.println(numEggs + " eggs = " + (numEggs / 6) + " cartons of half a dozen");
}

/* Your code goes here */

}
}
}

1 Answer

7 votes

Final answer:

Here is the modified code:

catch (InputMismatchException e) {
System.out.println("Unexpected input: The TotalEggs program quits");
attemptsLeft = 0;
}
catch (Exception e) {
System.out.println(e.getMessage());
attemptsLeft--;
}

Step-by-step explanation:

In the given code, the while loop is used to make up to three attempts to read an integer divisible by 6 from input into the variable numEggs.

To handle different types of exceptions, multiple exception handlers are used. The first catch block catches an InputMismatchException which occurs when the input is not an integer.

It outputs the message 'Unexpected input: The TotalEggs program quits' and sets attemptsLeft to 0. The second catch block catches any other exceptions and outputs the message of the exception, subtracting 1 from attemptsLeft.

Here is the modified code:

catch (InputMismatchException e) {
System.out.println("Unexpected input: The TotalEggs program quits");
attemptsLeft = 0;
}
catch (Exception e) {
System.out.println(e.getMessage());
attemptsLeft--;
}
User Tsds
by
8.2k points