LoslegenKostenlos loslegen

Finally

Ändere jetzt den vorherigen SplitTheBill-Rechner aus der letzten Übung so, dass ein finally verwendet wird, um den Betrag pro Person auszugeben – selbst wenn eine Exception abgefangen wurde.

Diese Übung ist Teil des Kurses

Datentypen und Exceptions in Java

Kurs anzeigen

Anleitung zur Übung

  • Füge ein try und den Beginn des try-Codeblocks hinzu.
  • Schließe den catch-Codeblock ab und füge einen finally-Codeblock hinzu.
  • Schließe den finally-Codeblock ab.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

class SplitTheBill {
	public static void main(String[] args) {
		BigDecimal bill = new BigDecimal(125.50);
		computeEachBill(bill, 5);
		computeEachBill(bill, 0);
	}

	public static void computeEachBill(BigDecimal bill, int people) {
		BigDecimal individualBill = new BigDecimal(0);
		BigDecimal numPeople = new BigDecimal(people);
		// Add a try and the beginning of the try code block
		____ ____
			individualBill = bill.divide(numPeople);
        } catch (ArithmeticException e) {
			System.out.println("You didn't provide a positive number of people to split the bill among. Assuming 2 people.");
			numPeople = new BigDecimal(2);
			individualBill = bill.divide(numPeople);
			// End the catch code block and add a finally block
        ____ ____ ____
			System.out.println("Bill for each of " + numPeople + " persons is: " + individualBill);
		// End the finally block
        ____
	}
}
Code bearbeiten und ausführen