1. The if and if…else Statements

    In Java, when you want to take an action if a Boolean expression is true, you use an if statement. If you want to take an action when a Boolean expression is true but take a different action when the expression is false, you use an if…else statement.

    The if Statement
    The simplest statement you can use to make a decision is the if statement. An if statement is sometimes called a single-alternative selection because there is only one alternative—the true alternative.
    if(quizScore == 10) System.out.println("The score is perfect");
    if(quizScore == 10); // Semi colon at the end of if statement is wrong System.out.println("The score is perfect"); // This statement executes no matter what the value of quizScore is

    The if…else Statement
    In Java, the if…else statement provides the mechanism to perform one action when a Boolean expression evaluates as true and a different action when a Boolean expression evaluates as false. In other words, you use an if…else statement for a dual-alternative selection. For example, you would use an if…else statement if you wanted to display one message when the value of quizScore is 10 and a different message when it is not.
    if(quizScore == 10) System.out.println("The score is perfect"); else System.out.println("It's not perfect!");
    Using Multiple Statements in if and if…else Clauses
    Often, you want to take more than one action following the evaluation of a Boolean expression within an if statement. For example, you might want to display several separate lines of output or perform several mathematical calculations. To execute more than one statement that depends on the evaluation of a Boolean expression, you use a pair of curly braces to place the dependent statements within a block.
    if(hoursWorked > FULL_WEEK) { regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate; }
    When you fail to block statements that should depend on an if, and you also use an else clause, the program will not compile. For example, consider the following code:
    if(hoursWorked > FULL_WEEK) regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked – FULL_WEEK) * OT_RATE * rate; // This statement does not depend on the if, so the else is illegal. else regularPay = FULL_WEEK * rate;
    import java.util.Scanner; public class Payroll { public static void main(String[] args) { double rate; double hoursWorked; double regularPay; double overtimePay; final int FULL_WEEK = 40; final double OT_RATE = 1.5; Scanner keyboard = new Scanner(System.in); System.out.print("How many hours did you work this week? "); hoursWorked = keyboard.nextDouble(); System.out.print("What is your regular pay rate? "); rate = keyboard.nextDouble(); if(hoursWorked > FULL_WEEK) { regularPay = FULL_WEEK * rate; overtimePay = (hoursWorked - FULL_WEEK) * OT_RATE * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } System.out.println("Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); } }
    When you block statements, you must remember that any variable you declare within a block is local to that block. For example, the following code segment contains a variable named sum that is local to the block following the if. The last println() statement causes an error because the sum variable is not recognized:
    if(a == b) { int sum = a + b; System.out.println ("The two variables are equal"); } System.out.println("The sum is " + sum); // The variable sum is not recognized here.
    Nesting if and if…else Statements

    Within an if or an else clause, you can code as many dependent statements as you need, including other if and else statements. Statements in which a decision is contained inside either the if or else clause of another decision are nested if statements. Nested if statements are particularly useful when two or more conditions must be met before some action is taken.
    final int MIN_ITEMS = 3; final int MIN_VALUE = 1000; final int LARGE_BONUS= 50; final int MEDIUM_BONUS = 25; final int SMALL_BONUS = 10; int bonus = 0; if(itemsSold >= MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = LARGE_BONUS; else bonus = MEDIUM_BONUS; else bonus = SMALL_BONUS; // The last else goes with the first if.
  2. Using Logical AND and OR Operators

    The AND Operator
    For an alternative to some nested if statements, you can use the logical AND operator between two Boolean expressions to create a compound Boolean expression that is true when both of its operands are true. In Java, the AND operator is written as two ampersands ( && ). For example, the two statements shown in Figure work exactly the same way. In each case, both the itemsSold variable must be at least the minimum number of items required for a bonus and the totalValue variable must be at least the minimum required value for the bonus to be set to SALES_BONUS.
    if(itemsSold > MIN_ITEMS) if(totalValue >= MIN_VALUE) bonus = SALES_BONUS;
    if(itemsSold > MIN_ITEMS && totalValue >= MIN_VALUE) bonus = SALES_BONUS;

    The OR Operator
    When you want some action to occur even if only one of two conditions is true, you can use nested if statements, or you can use the logical OR operator, which is written as ||. The logical OR operator is used to create a compound Boolean expression that is true when at least one of its operands is true. For example, if you want to give a discount to any customer who satisfies at least one of two conditions—buying a minimum number of items or buying any number of items that total a minimum value—you can write the code using either of the ways shown in Figure.
    if(itemsBought >= MIN_ITEMS) discountRate = DISCOUNT; else if(itemsValue >= MIN_VALUE) discountRate = DISCOUNT; if(itemsBought >= MIN_ITEMS || itemsValue >= MIN_VALUE) discountRate = DISCOUNT;
    Short-Circuit Evaluation
    The expressions on each side of the && and || operators are evaluated only as far as necessary to determine whether the entire expression is true or false. This feature is called short-circuit evaluation. With the && operator, both Boolean expression operands must be true before the action in the result statement can occur. (The same is true for nested ifs, as you can see in Figure) When you use the && operator, if the first tested expression is false, the second expression is never evaluated because its value does not matter The || operator also uses short-circuit evaluation. In other words, because only one of the Boolean expressions in an || expression must be true to cause the dependent statements to execute, if the expression to the left of the || is true, then there is no need to evaluate the expression to the right of the ||.
    If you are using simple comparisons as the operands for the && or || operators you won’t notice that short-circuit evaluation is occurring. However, suppose that you have created two methods that return Boolean values and you use calls to those methods in an if statement, as in the following: if(method1() && method2()) System.out.println("OK"); Depending on the actions performed within the methods, it might be important to understand that in this case, if method1() is false, then method2() will not execute. If method2() contains statements that you want to execute no matter what the value of method1() is, then you should not use method2() as part of a compound condition, but should execute it on its own, as in the following example: boolean isMethod2True = method2(); if(method1() && isMethod2True) System.out.println("OK"); Similarly, in the following statement, if method1() returns true, then method2() will not execute because only one operand in an OR expression needs to be true in order for the entire expression to be true. if(method1() || method2()) System.out.println("OK");
  3. Using the switch Statement

    By nesting a series of if and else statements, you can choose from any number of alternatives. For example, suppose you want to display a student’s class year based on a stored number. Figure shows one possible implementation of the logic.
    if(year == 1) System.out.println("Freshman"); else if(year == 2) System.out.println("Sophomore"); else if(year == 3) System.out.println("Junior"); else if(year == 4) System.out.println("Senior"); else System.out.println("Invalid year");
    An alternative to using the series of nested if statements shown in Figure is to use the switch statement. The switch statement is useful when you need to test a single variable against a series of exact integer (including int, byte, and short types), character, or string values.
    The switch statement uses four keywords: • switch starts the statement and is followed immediately by a test expression enclosed in parentheses. • case is followed by one of the possible values for the test expression and a colon. • break optionally terminates a switch statement at the end of each case. • default optionally is used prior to any action that should occur if the test variable does not match any case
    You can leave out the break statements in a switch statement. However, if you omit the break and the program finds a match for the test variable, all the statements within the switch statement execute from that point forward. For example, if you omit each break statement in the code shown in Figure when the year is 3, the first two cases are bypassed, but Junior, Senior, and Invalid year all are output.
    switch(year) { case 1: System.out.println("Freshman"); break; case 2: System.out.println("Sophomore"); break; case 3: System.out.println("Junior"); break; case 4: System.out.println("Senior"); break; default: System.out.println("Invalid year"); }
    For example, the switch statement in Figure displays all the tasks that remain for the week after any particular day as well as displaying the default message. When day is Wednesday, all the following messages are displayed: Send out meeting reminders, Order snacks for delivery, Meeting 10 am, and Invalid day.
    switch(day) { case "Monday": System.out.println("Reserve room for Friday meeting"); case "Tuesday": System.out.println("Prepare PowerPoint slides"); case "Wednesday": System.out.println("Send out meeting reminders"); case "Thursday": System.out.println("Order snacks for delivery"); case "Friday": System.out.println("Meeting 10 am"); default: System.out.println("Invalid day"); }
    You do not need to write code for each case in a switch statement. For example, suppose that the supervisor for departments 1, 2, and 3 is Jones, but other departments have different supervisors. In that case, you might use the code in Figure.
    int department; String supervisor; // Statements to get department go here switch(department) { case 1: case 2: case 3: supervisor = "Jones"; break; case 4: supervisor = "Staples"; break; case 5: supervisor = "Tejano"; break; default: System.out.println("Invalid department code"); }
  4. Using the Conditional and NOT Operators

    Besides using if statements and switch statements, Java provides one more way to make decisions. The conditional operator requires three expressions separated with a question mark and a colon; it is used as an abbreviated version of the if…else statement. As with the switch statement, you are never required to use the conditional operator; it is simply a convenient shortcut. The syntax of the conditional operator is:
    testExpression ? trueResult : falseResult; The first expression, testExpression, is a Boolean expression that is evaluated as true or false. If it is true, the entire conditional expression takes on the value of the expression following the question mark (trueResult). If the value of the testExpression is false, the entire expression takes on the value of falseResult. For example, suppose you want to assign the smaller of two values, a and b, to a variable named smallerNum. The expression you can use is: smallerNum = (a < b) ? a : b; When evaluating the expression a < b, if a is less than b, the entire conditional expression takes the value to the left of the colon, a, which then is assigned to smallerNum. If a is not less than b, then the expression assumes the value to the right of the colon, and b is assigned to smallerNum. You could achieve the same results with the following if…else statement: if(a < b) smallerNum = a; else smallerNum = b; The disadvantage to using the conditional operator is that, at least at first, it is more difficult to read. The advantage is the conciseness of the statement.
    Using the NOT Operator
    You use the NOT operator, which is written as the exclamation point ( ! ), to negate the result of any Boolean expression. Any expression that evaluates as true becomes false when preceded by the NOT operator, and accordingly, any false expression preceded by the NOT operator becomes true. For example, suppose a monthly car insurance premium is $200 if the driver is age 25 or younger and $125 if the driver is age 26 or older. Each of the if…else statements in Figure correctly assigns the premium values. if(age <= 25) premium = 200; else premium = 125; if(!(age <= 25)) premium = 125; else premium = 200; if(age >= 26) premium = 125; else premium = 200; if(!(age >= 26)) premium = 200; else premium = 125;
  5. Understanding Operator Precedence

    You can combine as many && or || operators in an expression as you need to make a decision. For example, if you want to award bonus points (defined as BONUS) to any student who receives a perfect score on any of four quizzes, you might write a statement like the following:
    if(score1 == PERFECT || score2 == PERFECT || score3 == PERFECT || score4 == PERFECT) bonus = BONUS; else bonus = 0; In this case, if at least one of the score variables is equal to the PERFECT constant, the student receives the bonus points.
    Although you can combine any number of && or || operations in an expression, special care must be taken when you mix them. You learned in Chapter 2 that arithmetic operations have higher and lower precedences, and an operator’s precedence makes a difference in how an expression is evaluated. For example, within an arithmetic expression, multiplication and division are always performed prior to addition or subtraction. In the same way, && has higher precedence than ||. Table shows the precedence of the operators you have used so far.
    PrecedenceOperator(s)Symbol(s)
    HighestLogical NOT!
    IntermediateMultiplication, division, modulus*/%
    Addition, subtraction+–
    Relational> < >= <=
    Equality== !=
    Logical AND&&
    Logical OR||
    LowestAssignment=

    For example, consider the program segments shown in Figure These code segments are intended to be part of an insurance company program that determines whether an additional premium should be charged to a driver who meets both of the following criteria: • Has more than two traffic tickets or is under 25 years old • Is male // Assigns extra premiums incorrectly if(trafficTickets > 2 || age < 25 && gender == 'M') extraPremium = 200; // The expression that uses the && operator is evaluated first. // Assigns extra premiums correctly if((trafficTickets > 2 || age < 25) && gender == 'M') extraPremium = 200; // The expression within the inner parentheses is evaluated first.
  6. Adding Decisions and Constructors to Instance Methods

    You frequently will want to use what you have learned about decision making to control the allowed values in objects’ fields. Whether values are assigned to objects by constructors or by mutator methods, you often will need to use decisions to restrict the values assigned to fields. For example, suppose that you create an Employee class as shown in Figure The class contains two fields that hold an employee number and pay rate. The constructor accepts values for these fields as parameters, but instead of simply assigning the parameters to the fields, the code determines whether each value is within the allowed limits for the field. If the Employee class in Figure also contained set methods for empNum and payRate, and the rules governing appropriate values were the same as the rules used in the constructor, then it would make sense for the decisions to be made in the set methods and to code the constructor to call the set methods. That way, the decisions would appear only once in the class, saving time and space. Additionally, if a change to the rules was needed in the future—for example, if different default values were desired for either of the fields—then the code would be changed in just one place, reducing the likelihood of error or inconsistency.
    public class Employee { private int empNum; private double payRate; public int MAX_EMP_NUM = 9999; public double MAX_RATE = 60.00; Employee(int num, double rate) { if(num <= MAX_EMP_NUM) empNum = num; else empNum = MAX_EMP_NUM; if(payRate <= MAX_RATE) payRate = rate; else payRate = 0; } public int getEmpNum() { return empNum; } public double getPayRate() { return payRate; } }
  7. You Do It Exercises

    import java.util.Scanner; public class AssignVolunteer { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int OTHER_CODE = 2; final String CLOTHING_PRICER = "Regina"; final String OTHER_PRICER = "Marco"; Scanner input = new Scanner(System.in); System.out.println("What type of donation is this?"); System.out.print("Enter " + CLOTHING_CODE + " for clothing, " + OTHER_CODE + " for anything else... "); donationType = input.nextInt(); if(donationType == CLOTHING_CODE) volunteer = CLOTHING_PRICER; else volunteer = OTHER_PRICER; System.out.println("You entered " + donationType); System.out.println("The volunteer who will price this item is " + volunteer); } }
    import java.util.Scanner; public class AssignVolunteer2 { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int OTHER_CODE = 2; final String CLOTHING_PRICER = "Regina"; 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 " + CLOTHING_CODE + " for clothing, " + OTHER_CODE + " for anything else... "); donationType = input.nextInt(); if(donationType == CLOTHING_CODE) { volunteer = CLOTHING_PRICER; message = "a clothing donation"; } else { volunteer = OTHER_PRICER; message = "a non-clothing donation"; } System.out.println("You entered " + donationType); System.out.println("This is " + message); System.out.println("The volunteer who will price this item is " + volunteer); } }
    import java.util.Scanner; public class AssignVolunteer3 { public static void main(String[] args) { int donationType; String volunteer; final int CLOTHING_CODE = 1; final int OTHER_CODE = 2; final String CLOTHING_PRICER = "Regina"; 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 " + CLOTHING_CODE + " for clothing, " + OTHER_CODE + " for anything else... "); donationType = input.nextInt(); if(donationType == CLOTHING_CODE) { volunteer = CLOTHING_PRICER; message = "a clothing donation"; } else { if(donationType == OTHER_CODE) { volunteer = OTHER_PRICER; message = "a non-clothing donation"; } else { 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 ShortCircuitTestAnd { public static void main(String[] args) { if(falseMethod() && trueMethod()) System.out.println("Both are true"); else System.out.println("Both are not true"); } public static boolean trueMethod() { System.out.println("Within trueMethod()"); return true; } public static boolean falseMethod() { System.out.println("Within falseMethod()"); return false; } }
    public class ShortCircuitTestOr { public static void main(String[] args) { if(falseMethod() || trueMethod()) System.out.println("Both are true"); else System.out.println("Both are not true"); } public static boolean trueMethod() { System.out.println("Within trueMethod()"); return true; } public static boolean falseMethod() { System.out.println("Within falseMethod()"); return false; } }
    import java.util.Scanner; public class AssignVolunteer4 { 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(); 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 DogTriathlonParticipant2 { private final int NUM_EVENTS; private static int totalCumulativeScore = 0; private String name; private int obedienceScore; private int conformationScore; private int agilityScore; private boolean doScoresAgree; private int total; private double avg; public DogTriathlonParticipant2(String name, int numEvents, int score1, int score2, int score3) { this.name = name; NUM_EVENTS = numEvents; int totalNot0 = 0; if(score1 != 0) totalNot0 = totalNot0 + 1; if(score2 != 0) totalNot0 = totalNot0 + 1; if(score3 != 0) totalNot0 = totalNot0 + 1; if(numEvents == totalNot0) doScoresAgree = true; else doScoresAgree = false; if(doScoresAgree) { obedienceScore = score1; conformationScore = score2; agilityScore = score3; } else { obedienceScore = 0; conformationScore = 0; agilityScore = 0; } total = obedienceScore + conformationScore + agilityScore; if(NUM_EVENTS == 0) avg = 0; else avg = (double) total / NUM_EVENTS; totalCumulativeScore = totalCumulativeScore + total; } public void display() { if(!doScoresAgree) System.out.println("\nNotice! Number of events for " + name + " does not agree with scores reported."); System.out.println(name + " participated in " + NUM_EVENTS + " events and has an average score of " + avg); System.out.println(" " + name + " has a total score of " + total + " bringing the total cumulative score to " + totalCumulativeScore); } }
    public class DogTriathlonParticipant3 { private final int NUM_EVENTS; private static int totalCumulativeScore = 0; private String name; private int obedienceScore; private int conformationScore; private int agilityScore; private boolean doScoresAgree; private int total; private double avg; public DogTriathlonParticipant3(String name, int numEvents, int score1, int score2, int score3) { this.name = name; if(numEvents == 0) NUM_EVENTS = 1; else NUM_EVENTS = numEvents; int totalNot0 = 0; switch(numEvents) { case 0: if(score1 == 0 && score2 == 0 && score3 == 0) doScoresAgree = true; else doScoresAgree = false; break; case 1: if(score1 == 0) if(score2 == 0 || score3 == 0) doScoresAgree = false; else doScoresAgree = true; else if(score2 == 0) if(score3 == 0) doScoresAgree = false; else doScoresAgree = true; else if(score3 == 0) doScoresAgree = true; else doScoresAgree = false; break; case 2: if(score1 == 0) if(score2 == 0 || score3 == 0) doScoresAgree = false; else doScoresAgree = true; else if(score2 == 0) if(score3 == 0) doScoresAgree = false; else doScoresAgree = true; else if(score3 == 0) doScoresAgree = true; else doScoresAgree = false; break; case 3: if(score1 != 0 && score2 != 0 && score3 != 0) doScoresAgree = true; else doScoresAgree = false; break; default: doScoresAgree = false; } if(doScoresAgree) { obedienceScore = score1; conformationScore = score2; agilityScore = score3; } else { obedienceScore = 0; conformationScore = 0; agilityScore = 0; } total = obedienceScore + conformationScore + agilityScore; if(NUM_EVENTS == 0) avg = 0; else avg = (double) total / NUM_EVENTS; totalCumulativeScore = totalCumulativeScore + total; } public void display() { if(!doScoresAgree) System.out.println("\nNotice! Number of events for " + name + " does not agree with scores reported."); System.out.println(name + " participated in " + NUM_EVENTS + " events and has an average score of " + avg); System.out.println(" " + name + " has a total score of " + total + " bringing the total cumulative score to " + totalCumulativeScore); } }
  8. Case Problems

    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()); } 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; Scanner input = new Scanner(System.in); System.out.print("Enter number of guests >> "); 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; } }
    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()); } 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; Scanner input = new Scanner(System.in); System.out.print("Enter 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; } }