Simonefleek / Zybooks

Random Number
0 stars 0 forks source link

Figure 4.10.2: Continue statement: Meal finder program that ensures items purchased is evenly divisible by the number of diners. #6

Open Simonefleek opened 7 months ago

Simonefleek commented 7 months ago

A continue statement in a loop causes an immediate jump to the loop condition check. A continue statement can sometimes improve the readability of a loop. The example below extends the previous meal finder program to find meal options for which the total number of items purchased is evenly divisible by the number of diners. The program also outputs all possible meal options, instead of just reporting the first meal option found.

Figure 4.10.2: Continue statement: Meal finder program that ensures items purchased is evenly divisible by the number of diners.

import java.util.Scanner;

public class MealSolverMultipleDiners { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); final int EMPANADA_COST = 3; final int TACO_COST = 4;

  int userMoney;
  int numTacos;
  int numEmpanadas;
  int mealCost;
  int maxEmpanadas;
  int maxTacos;
  int numOptions;
  int numDiners;

  numTacos = 0;
  numEmpanadas = 0;
  mealCost = 0;
  numOptions = 0;

  System.out.print("Enter money for meal: ");
  userMoney = scnr.nextInt();

  System.out.print("How many people are eating: ");
  numDiners = scnr.nextInt();

  maxEmpanadas = userMoney / EMPANADA_COST;
  maxTacos = userMoney / TACO_COST;

  for (numTacos = 0; numTacos <= maxTacos; ++numTacos) {
     for (numEmpanadas = 0; numEmpanadas <= maxEmpanadas; ++numEmpanadas) {

        // Total items  must be equally divisible by number of diners
        if (((numTacos + numEmpanadas) % numDiners) != 0) {
           continue;
        }

        mealCost = (numEmpanadas * EMPANADA_COST) + (numTacos * TACO_COST);

        if (mealCost == userMoney) {
           System.out.println("$" + mealCost + " buys " + numEmpanadas
                   + " empanadas and " + numTacos
                   + " tacos without change.");
           numOptions = numOptions + 1;
        }
     }
  }

  if (numOptions == 0) {
     System.out.println("You cannot buy a meal without having "
             + "change left over.");
  }

} }

Simonefleek commented 7 months ago

Enter money for meal: 60 How many people are eating: 3 $60 buys 12 empanadas and 6 tacos without change. $60 buys 0 empanadas and 15 tacos without change.

...

Enter money for meal: 54 How many people are eating: 2 $54 buys 18 empanadas and 0 tacos without change. $54 buys 10 empanadas and 6 tacos without change. $54 buys 2 empanadas and 12 tacos without change.