// BunchOfGrapesNoObjects.java public class BunchOfGrapesNoObjects { // Set up variables to keep track of three // bunches of grapes public static int numGrapesInBunch1; public static int numGrapesInBunch2; public static int numGrapesInBunch3; public static boolean isWashedBunch1; public static boolean isWashedBunch2; public static boolean isWashedBunch3; /************************************************ * There are two ways to write general methods * for the bunches of grapes. * * Method 1: have each method take in a parameter * that indicates which bunch of grapes we're working * with, and use a switch statement to operate * on the correct bunch. ************************************************/ // eatGrape: Get a grape from a bunch and eat it // Input: integer indicating which bunch {1, 2, 3} // Output: none public static void eatGrape(int whichBunch) { switch (whichBunch) { case 1: numGrapesInBunch1--; System.out.print("Yum, ate a grape. "); System.out.println(numGrapesInBunch1 + " left in this bunch."); break; case 2: numGrapesInBunch2--; System.out.print("Yum, ate a grape. "); System.out.println(numGrapesInBunch2 + " left in this bunch."); break; case 3: numGrapesInBunch3--; System.out.print("Yum, ate a grape. "); System.out.println(numGrapesInBunch3 + " left in this bunch."); break; default: // Eat non-existent grape? System.out.println("Invalid bunch: " + whichBunch); return; } } /************************************************ * Approach 2: write a different method for each * bunch of grapes. ************************************************/ public static void washBunch1() { isWashedBunch1 = true; System.out.println("This bunch is now clean!"); } public static void washBunch2() { isWashedBunch2 = true; System.out.println("This bunch is now clean!"); } public static void washBunch3() { isWashedBunch3 = true; System.out.println("This bunch is now clean!"); } /************************************************ * But both of these require a lot of repetition! * Also, every time I want another bunch of grapes, * I have to change both methods. This is * a) annoying: wastes programmer time * b) error-prone: what if you miss one method? * OOP solves this problem. See BunchOfGrapes.java. ************************************************/ public static void main(String args[]) { // Initialize the variables to represent the three bunches // bunches of grapes numGrapesInBunch1 = 20; numGrapesInBunch2 = 15; numGrapesInBunch3 = 22; isWashedBunch1 = true; isWashedBunch2 = false; isWashedBunch3 = false; // Eat a grape from bunch 1 eatGrape(1); // Eat a grape from bunch 3 eatGrape(3); // Was it dirty? if (!isWashedBunch3) { System.out.println("Ew! You ate a dirty grape."); washBunch3(); } // Try eating a grape from bunch 4 eatGrape(4); } }