1. Learning About the Loop Structure

    If making decisions is what makes programs seem smart, looping is what makes programs seem powerful. A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the loop body executes and the Boolean expression is evaluated again. The loop body can be a single statement, or a block of statements between curly braces. As long as the loop-controlling, Boolean expression is true, the statements in the loop body continue to execute. When the Boolean evaluation is false, the loop ends. One execution of any loop is called an iteration.

    In Java, you can use several mechanisms to create loops. In this chapter, you learn to use three types of loops: • A while loop, in which the loop-controlling Boolean expression is the first statement in the loop, evaluated before the loop body ever executes • A for loop, which is usually used as a concise format in which to execute loops • A do…while loop, in which the loop controlling Boolean expression is the last statement in the loop, evaluated after the loop body executes one time.
  2. Creating while Loops

    You can use a while loop to execute a body of statements continually as long as the Boolean expression that controls entry into the loop continues to be true. In Java, a while loop consists of the keyword while followed by a Boolean expression within parentheses, followed by the body of the loop. You can use a while loop when you need to perform a task either a predetermined or unpredictable number of times. • Sometimes a programmer knows precisely how many times a loop should execute. A loop that executes a specific number of times is a definite loop or a counted loop. • Sometimes a programmer does not know how many times a loop will execute because the number of iterations is determined while the program is running. Such a loop is an indefinite loop.
    Writing a Definite while Loop
    To write a definite loop, you initialize a loop control variable, which is a variable whose value determines whether loop execution continues. While the Boolean value that results from comparing the loop control variable and another value is true, the body of the while loop continues to execute. In the body of the loop, you must include a statement that alters the loop control variable; otherwise, the loop will never end. For example, the program segment shown in Figure displays the series of integers 1 through 10. The variable lcv is the loop control variable—it starts the loop holding a value of 1, and while the value remains under 11, lcv continues to be output and increased.
    int lcv; final int LIMIT = 11; lcv = 1; while(lcv < LIMIT) { System.out.println(lcv); lcv = lcv + 1; }
    When you write applications containing loops, it is easy to make mistakes. For example, executing the code shown in Figure causes the message Hello to be displayed forever (theoretically) because there is no code to end the loop. A loop that never ends is called an infinite loop.
    while(4 > 2) { System.out.println("Hello"); }
    To prevent a while loop from executing infinitely, three separate actions must occur: • A loop control variable is initialized to a starting value. • The loop control variable is tested in the while statement. • The loop control variable is altered within the body of the loop. The variable must be altered so that the test expression eventually can evaluate to false and the loop can end.
    loopCount = 1; // Loop control variable initialized while(loopCount < 3) // Loop control variable tested { System.out.println("Hello"); loopCount = loopCount + 1; // Loop control variable altered }

    Pitfall: Failing to Alter the Loop Control Variable Within the Loop Body
    It is important that the loop control variable be altered within the body of the loop. Figure shows the same code as in previous Figure, but the curly braces have been eliminated. In this case, the while loop body ends at the semicolon that appears at the end of the output statement. Adding 1 to the loopCount is no longer part of a block that contains the loop, so the value of loopCount never changes, and an infinite loop is created.
    loopCount = 1; while(loopCount < 3) System.out.println("Hello"); loopCount = loopCount + 1; // Loop control variable is not altered in the loop.
    Pitfall: Unintentionally Creating a Loop with an Empty Body
    As with the decision-making if statement that you learned about in Chapter 5, placement of the statement-ending semicolon is important when you work with the while statement. If a semicolon is mistakenly placed at the end of the partial statement while(loopCount < 3);, as shown in Figure 6-6, the loop is also infinite. This loop has an empty body, or a body with no statements in it. So, the Boolean expression is evaluated, and because it is true, the loop body is entered. Because the loop body is empty, no action is taken, and the Boolean expression is evaluated again. Nothing has changed, so it is still true, the empty body is entered, and the infinite loop continues.
    loopCount = 1; while(loopCount < 3); // This semicolon causes the loop to have an empty body. { System.out.println("Hello"); loopCount = loopCount + 1; }
    Altering a Definite Loop’s Control Variable
    A definite loop is a counter-controlled loop because the loop control variable is changed by counting. It is very common to alter the value of a loop control variable by adding 1 to it, or incrementing the variable. However, not all loops are controlled by adding 1. The loop shown in Figure 6-7 displays Hello twice, just as the loop in Figure does, but its loop is controlled by subtracting 1 from a loop control variable, or decrementing it.
    loopCount = 3; while(loopCount > 1) { System.out.println("Hello"); loopCount = loopCount - 1; }
    Writing an Indefinite while Loop
    Often, the value of a loop control variable is not altered by adding to it or subtracting from it, but instead is altered by some other event. Such a loop is an event-controlled loop. An event-controlled loop is a type of indefinite loop because you don’t know how many times it eventually will repeat during each program execution. For example, perhaps you want to continue asking a user questions as long as the response is correct, but want to stop when a response is incorrect. In this case, while you are writing the program, you do not know whether the loop eventually will be executed two times or 200 times.
    import java.util.Scanner; public class BankBalance { public static void main(String[] args) { double balance; int response; int year = 1; final double INT_RATE = 0.03; Scanner keyboard = new Scanner(System.in); System.out.print("Enter initial bank balance > "); balance = keyboard.nextDouble(); System.out.println("Do you want to see next year's balance?"); System.out.print("Enter 1 for yes"); System.out.print(" or any other number for no >> "); response = keyboard.nextInt(); while(response == 1) { balance = balance + balance * INT_RATE; System.out.println("After year " + year + " at " + INT_RATE + " interest rate, balance is $" + balance); year = year + 1; System.out.println("\nDo you want to see the balance " + "at the end of another year?"); System.out.print("Enter 1 for yes"); System.out.print(" or any other number for no >> "); response = keyboard.nextInt(); } } }
    Validating Data
    Programmers commonly use indefinite loops when validating input data. Validating data is the process of ensuring that a value falls within a specified range. For example, suppose you require a user to enter a value no greater than 3. Figure shows an application that does not progress past the data entry loop until the user enters a correct value. If the user enters 3 or less at the first prompt, the loop never executes. However, if the user enters a number greater than 3, the loop executes, providing the user with another chance to enter a correct value.
    import java.util.Scanner; public class EnterSmallValue { public static void main(String[] args) { int userEntry; final int LIMIT = 3; Scanner input = new Scanner(System.in); System.out.print("Please enter an integer no higher than " + LIMIT + " > "); userEntry = input.nextInt(); while(userEntry > LIMIT) // The while statement controls the loop { System.out.println("The number you entered was too high"); System.out.print("Please enter an integer no higher than " + LIMIT + " > "); userEntry = input.nextInt(); } // The loop body is between the curly braces. System.out.println("You correctly entered " + userEntry); } }
  3. Using Shortcut Arithmetic Operators

    Programmers commonly need to increase the value of a variable in a program. As you saw in the previous section, many loops are controlled by continually adding 1 to some variable, as in count = count + 1;. Incrementing a variable in a loop to keep track of the number of occurrences of some event is also known as counting. Similarly, in the looping bank balance program shown in Figure, the program not only incremented the year variable by adding 1, it also increased the bank balance by an interest amount with the statement balance = balance + balance * INT_RATE;. In other words, the bank balance became its old value plus a new interest amount; the process of repeatedly increasing a value by some amount is known as accumulating. The statement count += 1; is identical in meaning to count = count + 1. The += is the add and assign operator; it adds and assigns in one operation. Similarly, balance += balance * INT_RATE; increases a balance by the INT_RATE percentage. Besides using the shortcut operator +=, you can use the subtract and assign operator ( -= ), the multiply and assign operator ( *= ), the divide and assign operator ( /= ), and the remainder and assign operator ( %= ). E When you want to increase a variable’s value by exactly 1, you can use two other shortcut operators—the prefix ++, also known as the prefix increment operator, and the postfix ++, also known as the postfix increment operator. To use a prefix ++, you type two plus signs before the variable name. The statement someValue = 6; followed by ++someValue; results in someValue holding 7—one more than it held before you applied the ++. To use a postfix ++, you type two plus signs just after a variable name. The statements anotherValue = 56; anotherValue++; result in anotherValue containing 57. Figure shows four ways you can increase a value by 1; each method produces the same result. You are never required to use shortcut operators; they are merely a convenience.
    int value; value = 24; ++value; // Result: value is 25 value = 24; value++; // Result: value is 25 value = 24; value = value + 1; // Result: value is 25 value = 24; value += 1; // Result: value is 25
    When you use the prefix ++, the result is calculated, and then its value is used. For example, consider the following statements: b = 4; c = ++b; The result is that both b and c hold the value 5 because b is increased to 5 and then the value of the expression is assigned to c. When you use the postfix ++, the value of the expression before the increase is stored. For example, consider these statements: b = 4; c = b++; The result is still that b is 5, but c is only 4. The value of b is assigned to c and then b is incremented. In other words, if b = 4, the value of b++ is also 4, but after the statement is completed, the value of b is 5.
    public class PrefixPostfixDemo { public static void main(String[] args) { int myNumber, answer; myNumber = 17; System.out.println("Before incrementing, myNumber is " + myNumber); answer = ++myNumber; System.out.println("After prefix increment, myNumber is " + myNumber); System.out.println(" and answer is " + answer); myNumber = 17; System.out.println("Before incrementing, myNumber is " + myNumber); answer = myNumber++; System.out.println("After postfix increment, myNumber is " + myNumber); System.out.println(" and answer is " + answer); } }
  4. Creating a for Loop

    A for loop is a special loop that is convenient to use when a definite number of loop iterations is required; it provides a concise way to create a counter-controlled loop. Although a while loop also can be used to meet this requirement, the for loop provides you with a shorthand notation for this type of loop. When you use a for loop, you can indicate the starting value for the loop control variable, the test condition that controls loop entry, and the expression that alters the loop control variable—all in one convenient place.
    You begin a for loop with the keyword for followed by a set of parentheses. Within the parentheses are three sections separated by exactly two semicolons. The three sections are usually used for the following: • Initializing the loop control variable • Testing the loop control variable • Updating the loop control variable The body of the for statement follows the parentheses. As with an if statement or a while loop, you can use a single statement as the body of a for loop, or you can use a block of statements enclosed in curly braces. Many programmers recommend that you always use a set of curly braces to surround the body of a for loop for clarity, even when the body contains only a single statement. You should use the conventions recommended by your organization.
    for(val = 1; val < 11; ++val) { System.out.println(val); } val = 1; while(val < 11) { System.out.println(val); ++val; }
    After initialization, program control passes to the middle, or test section, of the for statement that lies between the two semicolons. If the Boolean expression found there evaluates to true, the body of the for loop is entered. In the program segment shown in Figure 6-18, val initially is set to 1, so when val < 11 is tested, it evaluates to true. The loop body displays val. In this example, the loop body is a single statement, so no curly braces are needed (although they could be added). After the loop body executes, the final one-third of the for loop that follows the second semicolon executes, and val is increased to 2. Following the third section in the for statement, program control returns to the second section, where val is compared to 11 a second time. Because val is still less than 11, the body executes: val (now 2) is displayed, and then the third, altering portion of the for loop executes again. The variable val increases to 3, and the for loop continues. Eventually, when val is not less than 11 (after 1 through 10 have been displayed), the for loop ends, and the program continues with any statements that follow the for loop.
    Unconventional for Loops
    Although the three sections of the for loop are most commonly used to hold single expressions for initializing, testing, and incrementing, you also can perform the following tasks: • Initialization of more than one variable in the first section of the for statement by placing commas between the separate statements, as in the following: for(g = 0, h = 1; g < 6; ++g) • You can declare a variable within a for statement, as in the following: for(int val = 1; val < 11; ++val) Programmers often use this technique when the loop control variable is not needed in any other part of the program. If you declare a variable within a for statement, the variable can only be used in the block that depends on the for statement; when the block ends, the variable goes out of scope. • Performance of more than one test using compound conditions in the second section, as in the following: for(g = 0; g < 3 && h > 1; ++g) • Decrementation or performance of some other task in the third section, as in the following: for(g = 5; g >= 1; --g) • Performing multiple actions in the third section, separated by commas, as in the following: for(g = 0; g < 10; ++g, ++h, sum += g) • You might use method calls in any section of the for statement, as in the following example. Here, the isFinished() method would be required to return a Boolean value and the alter() method would be required to return a data type accepted by x. for(x = initMethod(); isFinished(); x = alter(x)) • You can leave one or more portions of a for loop empty, although the two semicolons are still required as placeholders. For example, if x has been initialized in a previous program statement, you might write the following: for(; x < 10; ++x) You might encounter for loops in which all three sections of the for statement are left empty. For example, consider the Clock class in Figure 6-19. The program contains a for loop that is meant to execute infinitely and display a clock with an updated time every second. Within the loop, the current time is retrieved using the LocalDateTime class. If the getSecond() value has changed since the last loop execution, the hour, minute, and second are displayed and the prevSec variable is updated.
    The clock application
    import java.time.*; public class Clock { public static void main(String[] args) { LocalDateTime now; int nowSec; int prevSec = 0; for (;;) { now = LocalDateTime.now(); nowSec = now.getSecond(); if(nowSec != prevSec) { System.out.println(now.getHour() + " : " + now.getMinute() + " : " + nowSec); prevSec = nowSec; } } } }
  5. Learning How and When to Use a do…while Loop

    Sometimes, you might need to ensure that a loop body executes at least one time. If so, you want to write a loop that checks at the “bottom” of the loop after the first iteration. The do…while loop is such a loop; it is a posttest loop—one in which the loop control variable is tested after the loop body executes.
    import java.util.Scanner; public class BankBalance2 { public static void main(String[] args) { double balance; int response; int year = 1; final double INT_RATE = 0.03; Scanner keyboard = new Scanner(System.in); System.out.print("Enter initial bank balance > "); balance = keyboard.nextDouble(); keyboard.nextLine(); do // The keyword do starts the loop. { balance = balance + balance * INT_RATE; System.out.println("After year " + year + " at " + INT_RATE + " interest rate, balance is $" + balance); year = year + 1; System.out.println("\nDo you want to see the balance " + "at the end of another year?"); System.out.println("Enter 1 for yes"); System.out.print(" or any other number for no >> "); response = keyboard.nextInt(); } while(response == 1); // The loop control variable is tested after the loop body executes. } }
  6. Learning About Nested Loops

    Just as if statements can be nested, so can loops. You can place a while loop within a while loop, a for loop within a for loop, a while loop within a for loop, or any other combination. When loops are nested, each pair contains an inner loop and an outer loop. The inner loop must be entirely contained within the outer loop;
    import java.util.Scanner; public class BankBalanceByRateAndYear { public static void main(String[] args) { double initialBalance; double balance; int year; double interest; final double LOW = 0.02; final double HIGH = 0.05; final double INCREMENT = 0.01; final int MAX_YEAR = 4; Scanner keyboard = new Scanner(System.in); System.out.print("Enter initial bank balance > "); initialBalance = keyboard.nextDouble(); keyboard.nextLine(); for(interest = LOW; interest <= HIGH; interest += INCREMENT) // The loop that varies interest is the outer loop. { balance = initialBalance; System.out.println("\nWith an initial balance of $" + balance + " at an interest rate of " + interest); for(year = 1; year <= MAX_YEAR; ++ year) // The loop that varies year is the inner loop. { balance = balance + balance * interest; System.out.println("After year " + year + " balance is $" + balance); } } } }
  7. Improving Loop Performance

    Whether you decide to use a while, for, or do…while loop in an application, you can improve loop performance by doing one or more of the following things: • Making sure the loop does not include unnecessary operations or statements • Considering the order of evaluation for short-circuit operators • Making a comparison to 0 • Employing loop fusion to combine loops If a loop executes only a few times, implementing the suggestions presented in this section won’t change program performance very much, but for a large-scale application in which speed is important, some of these suggestions can make a difference. Thinking about these suggestions also improves your understanding of how loops work.
    Avoiding Unnecessary Operations
    You can make loops more efficient by not using unnecessary operations or statements, either within a loop’s tested expression or within the loop body. For example, suppose a loop should execute while x is less than the sum of two integers, a and b. The loop could be written as: while(x < a + b) // sum is recalculated for every iteration // loop body If this loop executes 1,000 times, then the expression a + b is calculated 1,000 times. Instead, if you use the following code, the results are the same, but the arithmetic is performed only once: int sum = a + b; // sum is calculated just once while(x < sum) // loop body Of course, if a or b is altered in the loop body, then a new sum must be calculated with every loop iteration. However, if the sum of a and b is fixed prior to the start of the loop, then writing the code the second way is far more efficient.
    Comparing to Zero
    Making a comparison to 0 is faster than making a comparison to any other value. Therefore, if your application makes comparison to 0 feasible, you can improve loop performance by structuring your loops to compare the loop control variable to 0 instead of some other value. For example, a loop that performs based on a variable that varies from 0 up to 100,000 executes the same number of times as a loop based on a variable that varies from 100,000 down to 0. However, the second loop performs slightly faster. Comparing a value to 0 instead of other values is faster because in a compiled language, condition flags for the comparison are set once, no matter how many times the loop executes. Comparing a value to 0 is faster than comparing to other values, no matter which comparison operator you use—greater than, less than, equal to, and so on. Figure contains a program that tests the execution times of two nested do-nothing loops. The program declares variables to hold a startTime before each nested loop begins and an endTime after each nested loop is complete. Before each nested loop execution, the current time is retrieved from the LocalDateTime class and the value of the nanoseconds (billionths of a second) is retrieved using the getNano() method. After each nested loop repeats 100,000 times, the current time is retrieved again. Subtracting one time from the other computes the interval, and dividing by 1 million converts nanoseconds to more readable milliseconds.
    import java.time.*; public class CompareLoopTimes { public static void main(String[] args) { int startTime, endTime; final int REPEAT = 100_000; final int FACTOR = 1_000_000; LocalDateTime now; now = LocalDateTime.now(); startTime = now.getNano(); for(int x = 0; x <= REPEAT; ++x) for(int y = 0; y <= REPEAT; ++y); // Nested do-nothing loop now = LocalDateTime.now(); endTime = now.getNano(); System.out.println("Time for loops starting from 0: " + ((endTime - startTime) / FACTOR) + " milliseconds"); now = LocalDateTime.now(); startTime = now.getNano(); for(int x = REPEAT; x >= 0; ––x) for(int y = REPEAT; y >= 0; ––y); // Nested do-nothing loop now = LocalDateTime.now(); endTime = now.getNano(); System.out.println("Time for loops ending with 0: " + ((endTime - startTime) / FACTOR) + " milliseconds"); } }
    Employing Loop Fusion
    Loop fusion is the technique of combining two loops into one. For example, suppose you want to call two methods 100 times each. You can set a constant named TIMES to 100 and use the following code: for(int x = 0; x < TIMES; ++x) method1(); for(int x = 0; x < TIMES; ++x) method2(); However, you can also use the following code: for(int x = 0; x < TIMES; ++x) { method1(); method2(); }
  8. You Do It Exercises

    import java.util.Scanner; public class AssignVolunteer5 { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int FURNITURE_CODE = 2; final int ELECTRONICS_CODE = 3; final int OTHER_CODE = 4; final String CLOTHING_PRICER = "Regina"; final String FURNITURE_PRICER = "Walter"; final String ELECTRONICS_PRICER = "Lydia"; final String OTHER_PRICER = "Marco"; String message; Scanner input = new Scanner(System.in); System.out.println("What type of donation is this?"); System.out.print("Enter an integer... "); donationType = input.nextInt(); while(donationType < CLOTHING_CODE || donationType > OTHER_CODE) { System.out.println("You entered " + donationType + " which is not a valid donation type"); System.out.print("Please enter a value between " + CLOTHING_CODE + " and " + OTHER_CODE + "... "); System.out.print("Enter an integer... "); donationType = input.nextInt(); } switch(donationType) { case(CLOTHING_CODE): volunteer = CLOTHING_PRICER; message = "a clothing donation"; break; case(FURNITURE_CODE): volunteer = FURNITURE_PRICER; message = "a furniture donation"; break; case(ELECTRONICS_CODE): volunteer = ELECTRONICS_PRICER; message = "an electronics donation"; break; case(OTHER_CODE): volunteer = OTHER_PRICER; message = "another donation type"; break; default: volunteer = "invalid"; message = "an invalid donation type"; } System.out.println("You entered " + donationType); System.out.println("This is " + message); System.out.println("The volunteer who will price this item is " + volunteer); } }
    public class DemoIncrement { public static void main(String[] args) { int v = 4; int plusPlusV = ++v; v = 4; int vPlusPlus = v++; System.out.println("v is " + v); System.out.println("++v is " + plusPlusV); System.out.println("v++ is " + vPlusPlus); } }
    public class DemoIncrement2 { public static void main(String[] args) { int v = 4; int plusPlusV = ++v; v = 4; int vPlusPlus = v++; System.out.println("v is " + v); System.out.println("++v is " + plusPlusV); System.out.println("v++ is " + vPlusPlus); int w = 17, x = 17, y = 18; boolean compare1 = (++w == y); boolean compare2 = (x++ == y); System.out.println("First compare is " + compare1); System.out.println("Second compare is " + compare2); } }
    public class DivideEvenly { public static void main(String[] args) { final int LIMIT = 100; int var; System.out.print(LIMIT + " is evenly divisible by "); for(var = 1; var <= LIMIT; ++var) if(LIMIT % var == 0) System.out.print(var + " "); System.out.println(); } }
    public class DivideEvenly2 { public static void main(String[] args) { final int LIMIT = 100; int var; int number; System.out.print(LIMIT + " is evenly divisible by "); for(number = 1; number <= LIMIT; ++number) { System.out.print(number + " is evenly divisible by "); for(var = 1; var <= number; ++var) if(number % var == 0) System.out.print(var + " "); System.out.println(); } } }
    import java.time.*; public class TestFusedLoopTime { public static void main(String[] args) { int startTime, endTime; int x; final int REPEAT = 5_000_000; final int FACTOR = 1_000_000; LocalDateTime now; now = LocalDateTime.now(); startTime = now.getNano(); for(x = 0; x < REPEAT; ++x) method1(); for(x = 0; x < REPEAT; ++x) method2(); now = LocalDateTime.now(); endTime = now.getNano(); System.out.println("Time for loops executed separately: " + ((endTime - startTime) / FACTOR) + " milliseconds"); now = LocalDateTime.now(); startTime = now.getNano(); for(x = 0; x < REPEAT; ++x) { method1(); method2(); } now = LocalDateTime.now(); endTime = now.getNano(); System.out.println("Time for loops executed in a block: " + ((endTime - startTime) / FACTOR) + " milliseconds"); } public static void method1() { } public static void method2() { } }
  9. Case Problems

    public class Event { public final static double HIGH_GUEST_PRICE = 35.00; public final static double LOW_GUEST_PRICE = 32.00; public final static int LARGE_EVENT = 50; private String eventNumber; private int guests; private double pricePerGuest; private double priceForEvent; public Event() { this("A000", 0); } public Event(String num, int guests) { setEventNumber(num); setGuests(guests); } public void setEventNumber(String num) { eventNumber = num; } public void setGuests(int gsts) { guests = gsts; if(isLargeEvent()) { pricePerGuest = LOW_GUEST_PRICE; priceForEvent = guests * LOW_GUEST_PRICE; } else { pricePerGuest = HIGH_GUEST_PRICE; priceForEvent = guests * HIGH_GUEST_PRICE; } } public String getEventNumber() { return eventNumber; } public int getGuests() { return guests; } public double getPriceForEvent() { return priceForEvent; } public double getPricePerGuest() { return pricePerGuest; } public boolean isLargeEvent() { boolean isLarge = false; if(guests >= LARGE_EVENT) isLarge = true; return isLarge; } }
    import java.util.Scanner; public class EventDemo { public static void main(String[] args) { String eventNum; int guests; eventNum = getEventNumber(); guests = getGuests(); Event e1 = new Event(eventNum, guests); eventNum = getEventNumber(); guests = getGuests(); Event e2 = new Event(eventNum, guests); eventNum = getEventNumber(); guests = getGuests(); Event e3 = new Event(eventNum, guests); displayDetails(e1); displayDetails(e2); displayDetails(e3); Event larger = new Event(); larger = getLarger(e1, e2); System.out.println("\nOf Event #" + e1.getEventNumber() + " with " + e1.getGuests() + " guests " + " and Event #" + e2.getEventNumber() + " with " + e2.getGuests() + "\n the larger is Event #" + larger.getEventNumber() + " with " + larger.getGuests()); larger = getLarger(e1, e3); System.out.println("\nOf Event #" + e1.getEventNumber() + " with " + e1.getGuests() + " guests " + " and Event #" + e3.getEventNumber() + " with " + e3.getGuests() + "\n the larger is Event #" + larger.getEventNumber() + " with " + larger.getGuests()); larger = getLarger(e2, e3); System.out.println("\nOf Event #" + e2.getEventNumber() + " with " + e2.getGuests() + " guests " + " and Event #" + e3.getEventNumber() + " with " + e3.getGuests() + "\n the larger is Event #" + larger.getEventNumber() + " with " + larger.getGuests()); for(int x = 0; x < e1.getGuests(); ++x) System.out.println("Please come to my event!"); } public static String getEventNumber() { String num; Scanner input = new Scanner(System.in); System.out.print("Enter event number >> "); num = input.nextLine(); return num; } public static int getGuests() { int guests; final int MIN_GUESTS = 5; final int MAX_GUESTS = 100; Scanner input = new Scanner(System.in); System.out.print("Enter number of guests >> "); guests = input.nextInt(); while(guests < MIN_GUESTS || guests > MAX_GUESTS) { System.out.println("The number of guests must be between " + MIN_GUESTS + " and " + MAX_GUESTS); System.out.print("Please renter >> "); guests = input.nextInt(); } input.nextLine(); return guests; } public static void displayDetails(Event e) { System.out.println("\nEvent #" + e.getEventNumber()); System.out.println("The price for an event with " + e.getGuests() + " guests at $" + e.getPricePerGuest() + " per guest is $" + e.getPriceForEvent()); System.out.println("Whether this is a large event is " + (e.getGuests() >= e.LARGE_EVENT)); } public static Event getLarger(Event e1, Event e2) { Event larger = e2; if(e1.getGuests() >= e2.getGuests()) larger = e1; return larger; } }
    public class Rental { public static final int MINUTES_IN_HOUR = 60; public static final int HOUR_RATE = 40; private String contractNumber; private int hours; private int extraMinutes; private double price; public Rental(String num, int minutes) { setContractNumber(num); setHoursAndMinutes(minutes); } public Rental() { this("A000", 0); } public void setContractNumber(String num) { contractNumber = num; } public void setHoursAndMinutes(int minutes) { hours = minutes / MINUTES_IN_HOUR; extraMinutes = minutes % MINUTES_IN_HOUR; if(extraMinutes <= HOUR_RATE) price = hours * HOUR_RATE + extraMinutes; else price = hours * HOUR_RATE + HOUR_RATE; } public String getContractNumber() { return contractNumber; } public int getHours() { return hours; } public int getExtraMinutes() { return extraMinutes; } public double getPrice() { return price; } }
    import java.util.Scanner; public class RentalDemo { public static void main(String[] args) { String contractNum; int minutes; contractNum = getContractNumber(); minutes = getMinutes(); Rental r1 = new Rental(contractNum, minutes); contractNum = getContractNumber(); minutes = getMinutes(); Rental r2 = new Rental(contractNum, minutes); contractNum = getContractNumber(); minutes = getMinutes(); Rental r3 = new Rental(contractNum, minutes); displayDetails(r1); displayDetails(r2); displayDetails(r3); System.out.println("Of Contract #" + r1.getContractNumber() + " with a time of " + r1.getHours() + " hours and " + r1.getExtraMinutes() + " minutes,\n and Contract #" + r2.getContractNumber() + " with a time of " + r2.getHours() + " hours and " + r2.getExtraMinutes() + " minutes,\n the one with the longer time is Contract #" + getLongerRental(r1, r2).getContractNumber()); System.out.println("Of Contract #" + r1.getContractNumber() + " with a time of " + r1.getHours() + " hours and " + r1.getExtraMinutes() + " minutes,\n and Contract #" + r3.getContractNumber() + " with a time of " + r3.getHours() + " hours and " + r3.getExtraMinutes() + " minutes,\n the one with the longer time is Contract #" + getLongerRental(r1, r3).getContractNumber()); System.out.println("Of Contract #" + r2.getContractNumber() + " with a time of " + r2.getHours() + " hours and " + r2.getExtraMinutes() + " minutes,\n and Contract #" + r3.getContractNumber() + " with a time of " + r3.getHours() + " hours and " + r3.getExtraMinutes() + " minutes,\n the one with the longer time is Contract #" + getLongerRental(r2, r3).getContractNumber()); int hoursInRental = r1.getHours(); for(int x = 0; x < hoursInRental; ++x) System.out.println("Coupon good for 10 percent off next rental"); } public static String getContractNumber() { String num; Scanner input = new Scanner(System.in); System.out.print("Enter contract number >> "); num = input.nextLine(); return num; } public static int getMinutes() { int minutes; final int LOW_MIN = 60; final int HIGH_MIN = 7200; Scanner input = new Scanner(System.in); System.out.print("Enter minutes >> "); minutes = input.nextInt(); while(minutes < LOW_MIN || minutes > HIGH_MIN) { System.out.println("Time must be between " + LOW_MIN + " minutes and " + HIGH_MIN + " minutes"); System.out.print("Please reenter minutes >> "); minutes = input.nextInt(); } return minutes; } public static void displayDetails(Rental r) { System.out.println("\nContract #" + r.getContractNumber()); System.out.println("For a rental of " + r.getHours() + " hours and " + r.getExtraMinutes() + " minutes, at a rate of " + r.HOUR_RATE + " the price is $" + r.getPrice()); } public static Rental getLongerRental(Rental r1, Rental r2) { Rental longer = new Rental(); int minutes1; int minutes2; minutes1 = r1.getHours() * Rental.MINUTES_IN_HOUR + r1.getExtraMinutes(); minutes2 = r2.getHours() * Rental.MINUTES_IN_HOUR + r2.getExtraMinutes(); if(minutes1 >= minutes2) longer = r1; else longer = r2; return longer; } }