1. Declaring an Array

    An array is a named list of data items that all have the same data type. Each data item is an element of the array. You declare an array variable in the same way you declare any simple variable, but you insert a pair of square brackets after the data type. For example, to declare an array of double values to hold sales figures for salespeople, you can write the following: double[] salesFigures; Similarly, to create an array of integers to hold student ID numbers, you can write the following: int[] idNums;
    Additionally, many programmers observe one of the following conventions to make it more obvious that the name represents a group of items: • Because arrays store multiple items, they often are named using a plural noun such as salesFigures. • Arrays often are named by adding a final word that implies a group, such as salesList, salesTable, or salesArray. After you create an array variable, you still need to reserve memory space. You use the same procedure to create an array that you use to create an object. Recall that when you create a class named Employee, you can declare an Employee object with a declaration such as: Employee oneWorker; However, that declaration does not actually create the oneWorker object. You create the oneWorker object when you use the keyword new and a call to the constructor, as in: oneWorker = new Employee(); Similarly, declaring an array and reserving memory space for it are two distinct processes. To reserve memory locations for 20 salesFigures values, you can declare the array variable and create the array with two separate statements as follows: double[] salesFigures; salesFigures = new double[20]; Alternatively, just as with objects, you can declare and create an array in one statement with the following: double[] salesFigures = new double[20]; The statement double[] salesFigures = new double[20]; reserves 20 memory locations for 20 double values. You can distinguish each salesFigures item from the others with a subscript. A subscript is an integer contained within square brackets that specifies one of an array’s elements. In Java, any array’s elements are numbered beginning with 0, so you can legally use any subscript from 0 through 19 when working with an array that has 20 elements. In other words, the first salesFigures array element is salesFigures[0] and the last salesFigures element is salesFigures[19].
    When you work with any individual array element, you treat it no differently from how you would treat a single variable of the same type. For example, to assign a value to the first salesFigures element in an array, you use a simple assignment statement, such as the following: salesFigures[0] = 2100.00; To display the last salesFigures element in an array of 20, you can write: System.out.println(salesFigures[19]); When programmers talk about these statements, they typically say things like, “salesFigures sub zero is assigned 2100.00,” and “salesFigures sub 19 is output.” In other words, they use sub as shorthand for with the subscript. When you declare or access an array, you can use any expression to represent the size, as long as the expression is an integer. Some other programming languages, such as C++, allow only named or unnamed constants to be used for the size when an array is declared. Java allows variables, arithmetic expressions, and method return values to be used as array sizes, which makes array declaration more flexible. For example, to declare a double array named moneyValues, you might use any of the following: • A literal integer constant; for example: double[] moneyValues = new double[10]; • A named integer constant; for example: double[] moneyValues = new double[NUMBER_ELS]; In this example, the constant NUMBER_ELS must have been declared previously and assigned a value. • An integer variable; for example: double[] moneyValues = new double[numberOfEls]; In this example, the variable numberOfEls must have been declared previously and assigned a value. • A calculation; for example: double[] moneyValues = new double[x + y * z]; In this example, the variables x, y, and z must have been declared previously and assigned values, and the result of the expression x + y * z must be an integer. • A method’s return value; for example: double[] moneyValues = new double[getElements()]; In this example, the method getElements() must return an integer.
  2. Initializing an Array

    A variable that has a primitive type, such as int, holds a value. A variable with a reference type, such as an array, holds a memory address where a value is stored. In other words, array names contain references, as do all Java object names. No memory address is assigned when you declare an array using only a data type, brackets, and a name. Instead, the array variable name has the value null, which means the identifier is not associated with a memory address. You can explicitly assign null to an array reference, but it is not required. For example, each of the following statements assigns null to someNums: int[] someNums; int[] someNums = null; When you use the keyword new to define an array, the array reference acquires a memory address value. For example, when you define someNums in the following statement, a memory address is assigned: int[] someNums = new int[10]; When you declare int[] someNums = new int[10];, someNums holds an address, but each element of someNums has a value of 0 by default because someNums is an integer array. The following default values are used for different array types: • Each element in an int array is assigned 0. • Each element in a double or float array is assigned 0.0. • Each element in a char array is assigned \u0000, which is the Unicode value for a null character. • Each element in a boolean array is assigned the value false. • Each element in an array of objects, including Strings, is assigned null by default. You already know how to assign a different value to a single element of an array, as in: someNums[0] = 46; You also can assign nondefault values to array elements upon creation. To initialize an array, you use an initialization list of values separated by commas and enclosed within curly braces. Providing values for all the elements in an array also is called populating the array. For example, if you want to create an array named multsOfTen and store the first six multiples of 10 within the array, you can declare the array as follows: int[] multsOfTen = {10, 20, 30, 40, 50, 60}; Notice the semicolon at the end of the statement. You don’t use a semicolon following a method’s closing curly brace, but you do use one following the closing brace of an array initialization list. When you populate an array upon creation by providing an initialization list, you do not give the array a size—the size is assigned based on the number of values you place in the initializing list. For example, the multsOfTen array just defined has a size of 6. Also, when you initialize an array, you do not need to use the keyword new; instead, new memory is assigned based on the length of the list of provided values. In Java, you cannot directly initialize part of an array. For example, you cannot create an array of 10 elements and initialize only five; you either must initialize every element or you must initialize none of them.
  3. Using Variable Subscripts with an Array
    If you treat each array element as an individual entity, there isn’t much of an advantage to declaring an array over declaring individual primitive type variables, such as those with the type int, double, or char. The power of arrays becomes apparent when you begin to use subscripts that are variables, rather than subscripts that are constant values. For example, suppose you declare an array of five integers that holds quiz scores, such as the following: int[] scoreArray = {2, 14, 35, 67, 85}; Suppose that the quiz administrator decides to increase each score by 3 to make up for a question that was determined to be invalid. To increase each scoreArray element by three points, you can write the following: final int INCREASE = 3; scoreArray[0] += INCREASE; scoreArray[1] += INCREASE; scoreArray[2] += INCREASE; scoreArray[3] += INCREASE; scoreArray[4] += INCREASE; With five scoreArray elements, this task is manageable, requiring only five statements. However, you can reduce the amount of program code needed by using a variable as the subscript. Then, you can use a loop to perform arithmetic on each array element, as in the following example: final int INCREASE = 3; for(sub = 0; sub < 5; ++sub) scoreArray[sub] += INCREASE; When there are 10 array elements, the subscript varies from 0 through 9; when there are 800 elements, the subscript varies from 0 through 799. Therefore, in an application that includes an array, it is convenient to declare a named constant equal to the size of the array and use it as a limiting value in every loop that processes the array. That way, if the array size changes in the future, you need to modify only the value stored in the named, symbolic constant, and you do not need to search for and modify the limiting value in every loop that processes the array. For example, suppose you declare an array and a named constant as follows: int[] scoreArray = {2, 14, 35, 67, 85}; final int NUMBER_OF_SCORES = 5; Then, the following two loops are identical: for(sub = 0; sub < 5; ++sub) scoreArray[sub] += INCREASE; for(sub = 0; sub < NUMBER_OF_SCORES; ++sub) scoreArray[sub] += INCREASE; As an even better option, you can use a field (instance variable) that is automatically assigned a value for every array you create; the length field contains the number of elements in the array. For example, when you declare an array using either of the following statements, the field scoreArray.length is assigned the value 5: int[] scoreArray = {2, 14, 35, 67, 85}; int[] scoreArray = new int[5]; Therefore, you can use the following loop to add 3 to every array element: for(sub = 0; sub < scoreArray.length; ++sub) scoreArray[sub] += INCREASE;
    Using the Enhanced for Loop
    In Chapter 6, you learned to use the for loop. Java also supports an enhanced for loop. This loop allows you to cycle through an array without specifying the starting and ending points for the loop control variable. For example, you can use either of the following statements to display every element in an array named scoreArray: for(int sub = 0; sub < scoreArray.length; ++sub) System.out.println(scoreArray[sub]); for(int val : scoreArray) System.out.println(val); In the second example, val is defined to be the same type as the array named following the colon. Within the loop, val takes on, in turn, each value in the array. You can read the second example as, “For each val in scoreArray, display val.” As a matter of fact, you will see the enhanced for loop referred to as a foreach loop. You can also use the enhanced for loop with more complicated Java objects, as you will see in the next section.
    Using Part of an Array
    Sometimes, you do not want to use every value in an array. For example, suppose that you write a program that allows a student to enter up to 10 quiz scores and then computes and displays the average. To allow for 10 quiz scores, you create an array that can hold 10 values, but because the student might enter fewer than 10 values, you might use only part of the array. Figure shows such a program.
    import java.util.*; public class AverageOfQuizzes { public static void main(String[] args) { int[] scores = new int[10]; int score = 0; int count = 0; int total = 0; final int QUIT = 999; final int MAX = 10; Scanner input = new Scanner(System.in); System.out.print("Enter quiz score or " + QUIT + " to quit >>"); score = input.nextInt(); while(score !=QUIT) // Loop continues as long as user does not enter QUIT value { scores[count] = score; total += scores[count]; ++count; if(count == MAX) score = QUIT; else { System.out.print("Enter next quiz score or " + QUIT + " to quit >> "); score = input.nextInt(); } } System.out.print("\nThe scores entered were: "); for(int x = 0; x < count; ++x) // The variable count is used to control output. System.out.print(scores[x] + " "); if(count != 0) System.out.println("\n The average is " + (total * 1.0 / count)); else System.out.println("No scores were entered."); } }
  4. Declaring and Using Arrays of Objects

    Just as you can declare arrays of simple types such as int or double, you can declare arrays that hold elements of objects. For example, assume you create the Employee class shown in Figure This class has two data fields (empNum and empSal), a constructor, and a get method for each field. You can create separate Employee objects with unique names, such as the following: Employee painter, electrician, plumber; Employee firstEmployee, secondEmployee, thirdEmployee; However, in many programs it is far more convenient to create an array of Employee objects. An array named emps that holds seven Employee objects can be defined as: Employee[] emps = new Employee[7]; This statement reserves enough computer memory for seven Employee objects named emps[0] through emps[6]. However, the statement does not actually construct those Employee objects; instead, you must call the seven individual constructors. According to the class definition shown in Figure 8-6, the Employee constructor requires two arguments: an employee number and a salary. If you want to number your Employees 101, 102, 103, and so on, and start each Employee at a salary of $15,000, the loop that constructs seven Employee objects is as follows: final int START_NUM = 101; final double STARTING_SALARY = 15_000; for(int x = 0; x < emps.length; ++x) emps[x] = new Employee(START_NUM + x, STARTING_SALARY); Unlike the Employee class in Figure, which contains a constructor that requires arguments, some classes contain only a default constructor, which might be supplied automatically when no other constructors are created or might be written explicitly. To construct an array of objects using a default constructor, you must still call the constructor using the keyword new for each declared array element. For example, suppose you have created a class named InventoryItem but have not written a constructor. To create an array of 1,000 InventoryItem objects, you would write the following: final int NUM_ITEMS = 1000; InventoryItem[] items = new InventoryItem[NUM_ITEMS]; for(int x = 0; x < NUM_ITEMS; ++x) items[x] = new InventoryItem(); You could use an initialization list to create an array of objects, as in the following example: InventoryItem[] items = {new InventoryItem(), new InventoryItem(), new InventoryItem()}; However, even with only a few objects in the array, this approach is unwieldy. Recall from Chapter 2 that Java allows underscores in numbers such as 15_000. The underscore is not required, but makes the number easier to read. As x varies from 0 through 6, each of the seven emps objects is constructed with an employee number that is 101 more than x, and each of the seven emps objects holds the same salary. Unlike the Employee class in Figure 8-6, which contains a constructor that requires arguments, some classes contain only a default constructor, which might be supplied automatically when no other constructors are created or might be written explicitly. To construct an array of objects using a default constructor, you must still call the constructor using the keyword new for each declared array element. For example, suppose you have created a class named InventoryItem but have not written a constructor. To create an array of 1,000 InventoryItem objects, you would write the following: final int NUM_ITEMS = 1000; InventoryItem[] items = new InventoryItem[NUM_ITEMS]; for(int x = 0; x < NUM_ITEMS; ++x) items[x] = new InventoryItem(); To use a method that belongs to an object that is part of an array, you insert the appropriate subscript notation after the array name and before the dot that precedes the method name. For example, to display data for seven Employees stored in the emps array, you can write the following: for(int x = 0; x < emps.length; ++x) System.out.println (emps[x].getEmpNum() + " " + emps[x].getSalary());
    public class Employee { private int empNum; private double empSal; Employee(int e, double s) { empNum = e; empSal = s; } public int getEmpNum() { return empNum; } public double getSalary() { return empSal; } }
    Using the Enhanced for Loop with Objects
    You can use the enhanced for loop to cycle through an array of objects. For example, to display data for seven Employees stored in the emps array, you can write the following: for(Employee worker : emps) System.out.println(worker.getEmpNum() + " " + worker.getSalary()); In this loop, worker is a local variable that represents each element of emps in turn. Using the enhanced for loop eliminates the need to use a limiting value for the loop and eliminates the need for a subscript following each element.
    Manipulating Arrays of Strings
    As with any other object, you can create an array of String objects. For example, you can store three company department names as follows: String[] deptNames = {"Accounting", "Human Resources", "Sales"}; You can access these department names with a subscript like any other array object. For example, you can use the following code to display the list of Strings stored in the deptNames array: for(int a = 0; a < deptNames.length; ++a) System.out.println(deptNames[a]); Notice that deptNames.length; refers to the length of the array deptNames (three elements) and not to the length of any String objects stored in the deptNames array. Remember: • Arrays use a length field (no parentheses follow). • String objects use a length() method. For example, if deptNames[0] is Accounting, then deptNames[0].length() is 10 because Accounting contains 10 characters.
  5. Searching an Array and Using Parallel Arrays

    Suppose that a company manufactures 10 items. When a customer places an order for an item, you need to determine whether the item number on the order form is valid. When you want to determine whether a variable holds one of many valid values, one option is to use a series of if statements to compare the variable to a series of valid values. If valid item numbers are sequential, such as 101 through 110, the following simple if statement that uses a logical AND expression can verify the order number and set a Boolean field to true: final int LOW = 101; final int HIGH = 110; boolean isValidItem = false; if(itemOrdered >= LOW && itemOrdered <= HIGH) isValidItem = true; In this example, the Boolean field isValidItem is used as a flag—a variable that holds a value as an indicator of whether some condition has been met. If the valid item numbers are nonsequential—for example, 101, 108, 201, and so on—you can code the following deeply nested if statement or a lengthy OR comparison to determine the validity of an item number: if(itemOrdered == 101) isValidItem = true; else if(itemOrdered == 108) isValidItem = true; else if(itemOrdered == 201) isValidItem = true; // and so on Instead of a long series of if statements, a more elegant solution is to compare the itemOrdered variable to a list of values in an array, a process called searching an array. You can initialize the array with the valid values using the following statement, which creates exactly 10 array elements with subscripts 0 through 9: int[] validValues = {101, 108, 201, 213, 266, 304, 311, 409, 411, 412}; After the list of valid values is initialized, you can use a for statement to loop through the array, and set a Boolean variable to true when a match is found: for(int x = 0; x < validValues.length; ++x) { if(itemOrdered == validValues[x]) isValidItem = true; } This simple for loop replaces the long series of if statements; it checks the itemOrdered value against each of the 10 array values in turn. Also, if a company carries 1,000 items instead of 10, nothing changes in the for statement—the value of validValues.length is updated automatically.
    Using Parallel Arrays
    As an added bonus, if you set up another array with the same number of elements and corresponding data, you can use the same subscript to access additional information. A parallel array is one with the same number of elements as another, and for which the values in corresponding elements are related. For example, if the 10 items your company carries have 10 different prices, you can set up an array to hold those prices as follows: double[] prices = {0.29, 1.23, 3.50, 0.69…}; The prices must appear in the same order as their corresponding item numbers in the validValues array. Now, the same for loop that finds the valid item number also finds the price, as shown in the application in Figure 8-9. In the for loop, notice that when the ordered item’s number is found in the validValues array, the itemPrice value is “pulled” from the prices array. In other words, if the item number is found in the second position in the validValues array, you can find the correct price in the second position in the prices array.
    import javax.swing.*; public class FindPrice { public static void main(String[] args) { final int NUMBER_OF_ITEMS = 10; int[] validValues = {101, 108, 201, 213, 266, 304, 311, 409, 411, 412}; double[] prices = {0.29, 1.23, 3.50, 0.69, 6.79, 3.19, 0.99, 0.89, 1.26, 8.00}; String strItem; int itemOrdered; double itemPrice = 0.0; boolean isValidItem = false; strItem = JOptionPane.showInputDialog(null, "Enter the item number you want to order"); itemOrdered = Integer.parseInt(strItem); for(int x = 0; x < NUMBER_OF_ITEMS; ++x) { if(itemOrdered == validValues[x]) { isValidItem = true; itemPrice = prices[x]; // Corresponding price is pulled from prices array } } if(isValidItem) JOptionPane.showMessageDialog(null, The price for item " + itemOrdered + " is $" + itemPrice); else JOptionPane.showMessageDialog(null, "Sorry - invalid item entered"); } }
    Searching an Array for a Range Match
    Searching an array for an exact match is not always practical. Suppose your company gives customer discounts based on the quantity of items ordered. Perhaps no discount is given for any order of fewer than a dozen items, but increasing discounts are available for orders of increasing quantities, as shown in Table. One awkward option is to create a single array to store the discount rates. You could use a variable named numOfItems as a subscript to the array, but the array would need hundreds of entries, as in the following example: double[] discounts = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.10, 0.10, 0.10 …};
    Total Quality OrderedDiscount
    1 to 12None
    13 to 4910%
    50 to 9914%
    100 to 19918%
    200 or more20%
    Thirteen zeroes are listed in the discounts array. The first array element has a 0 subscript and represents a zero discount for zero items. The next 12 discounts (for items 1 through 12) are also zero. When numOfItems is 13, discounts[numOfItems], or discounts[13], is 0.10. The array would store 37 copies of 0.10 for elements 13 through 49. The discounts array would need to be ridiculously large to hold an exact value for each possible quantity ordered. A better option is to create two corresponding arrays and perform a range match, in which you compare a value to the endpoints of numerical ranges to find the category in which a value belongs. For example, one array can hold the five discount rates, and the other array can hold five discount range limits. The Total Quantity Ordered column in Table 8-1 shows five ranges. If you use only the first figure in each range, you can create an array that holds five low limits: int[] discountRangeLimits = {1, 13, 50, 100, 200}; A parallel array can hold the five discount rates: double[] discountRates = {0, 0.10, 0.14, 0.18, 0.20}; Then, starting at the last discountRangeLimits array element, for any numOfItems greater than or equal to discountRangeLimits[4], the appropriate discount is discounts[4]. In other words, for any numOrdered less than discountRangeLimits[4], you should decrement the subscript and look in a lower range. Previous figure shows an application that uses the parallel arrays, and next figure shows a typical execution of the program.
    import javax.swing.*; public class FindDiscount { public static void main(String[] args) { final int NUM_RANGES = 5; int[] discountRangeLimits = { 1, 13, 50, 100, 200}; double[] discountRates = {0.00, 0.10, 0.14, 0.18, 0.20}; double customerDiscount; String strNumOrdered; int numOrdered; int sub = NUM_RANGES - 1; strNumOrdered = JOptionPane.showInputDialog(null, "How many items are ordered?"); numOrdered = Integer.parseInt(strNumOrdered); while(sub >= 0 && numOrdered < discountRangeLimits[sub]) --sub; customerDiscount = discountRates[sub]; JOptionPane.showMessageDialog(null, "Discount rate for " + numOrdered + " items is " + customerDiscount); } }
  6. Passing Arrays to and Returning Arrays from Methods

    You already have seen that you can use any individual array element in the same manner as you use any single variable of the same type. That is, if you declare an integer array as int[] someNums = new int[12];, you can subsequently display someNums[0], or increment someNums[1], or work with any element just as you do for any integer. Similarly, you can pass a single array element to a method in exactly the same manner as you pass any variable. Examine the PassArrayElement application shown in Figure and the output shown in Figure. The application creates an array of four integers and displays them. Then, the application calls the methodGetsOneInt() method four times, passing each element in turn. The method displays the number, changes the number to 999, and then displays the number again. Finally, back in the main() method, the four numbers are displayed again.
    public class PassArrayElement { public static void main(String[] args) { final int NUM_ELEMENTS = 4; int[] someNums = {5, 10, 15, 20}; int x; System.out.print("At start of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x]); System.out.println(); for(x = 0; x < NUM_ELEMENTS; ++x) methodGetsOneInt(someNums[x]); System.out.print("At end of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x]); System.out.println(); } public static void methodGetsOneInt(int one) { System.out.print("At start of method one is: " + one); one = 999; System.out.println(" and at end of method one is: " + one); } }
    public class PassArray { public static void main(String)[] args) { final int NUM_ELEMENTS = 4; int[] someNums = {5, 10, 15, 20}; int x; System.out.print("At start of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x]); System.out.println(); methodGetsArray(SomeNums); System.out.print("At end of main: "); for(x = 0; x < NUM_ELEMENTS; ++x) System.out.print(" " + someNums[x]); System.out.println(); } public static void methodGetsArray(int[] arr) // Brackets are used in the parameter list to show that an array is passed. { int x; System.out.print("At start of method arr holds: "); for(x = 0; x < arr.length; ++x) System.out.print(" " + arr[x]); System.out.println(); for(x = 0; x < arr.length; ++x) arr[x] = 888; System.out.print(" and at end of method arr holds: "); for(x = 0; x < arr.length; ++x) System.out.print(" " + arr[x]); System.out.println(); } }
    Returning an Array from a Method
    public static int[] getArray() { int[] scores = {90, 80, 70, 60}; return scores; }
    A method can return an array reference, and when it does, you include square brackets with the return type in the method header. For example, Figure shows a getArray() method that returns a locally declared array of ints. Square brackets are used as part of the return type; the return statement returns the array name without any brackets. When you call the getArray() method in Figure, you can store its returned value in any integer array reference. For example, you might declare an array and make the method call in the following statement: int[] scoresFromMethod = getArray();
  7. You Do It Exercises

    public class DemoArray { public static void main(String[] args) { double[] salaries = new double[4]; salaries[0] = 12.25; salaries[1] = 13.55; salaries[2] = 14.25; salaries[3] = 16.85; System.out.println("Salaries one by one are:"); System.out.println(salaries[0]); System.out.println(salaries[1]); System.out.println(salaries[2]); System.out.println(salaries[3]); } }
    public class DemoArray2 { public static void main(String[] args) { double[] salaries = {12.25, 13.55, 14.25, 16.85}; System.out.println("Salaries one by one are:"); System.out.println(salaries[0]); System.out.println(salaries[1]); System.out.println(salaries[2]); System.out.println(salaries[3]); System.out.println(salaries[4]); } }
    public class DemoArray3 { public static void main(String[] args) { double[] salaries = {12.25, 13.55, 14.25, 16.85}; System.out.println("Salaries one by one are:"); for(int x = 0; x < salaries.length; ++x) System.out.println(salaries[x]); } }
    public class BowlingTeam { private String teamName; private String[] members = new String[4]; public void setTeamName(String team) { teamName = team; } public String getTeamName() { return teamName; } public void setMember(int number, String name) { members[number] = name; } public String getMember(int number) { return members[number]; } }
    import java.util.*; public class BowlingTeamDemo { public static void main(String[] args) { String name; BowlingTeam bowlTeam = new BowlingTeam(); int x; final int NUM_TEAM_MEMBERS = 4; Scanner input = new Scanner(System.in); System.out.print("Enter team name >> "); name = input.nextLine(); bowlTeam.setTeamName(name); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) { System.out.print("Enter team member's name >> "); name = input.nextLine(); bowlTeam.setMember(x, name); } System.out.println("\nMembers of team " + bowlTeam.getTeamName()); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) System.out.print(bowlTeam.getMember(x) + " "); System.out.println(); } }
    import java.util.*; public class BowlingTeamDemo2 { public static void main(String[] args) { String name; final int NUM_TEAMS = 4; BowlingTeam[] teams = new BowlingTeam[NUM_TEAMS]; int x; int y; final int NUM_TEAM_MEMBERS = 4; Scanner input = new Scanner(System.in); for(y = 0; y < NUM_TEAMS; ++y) { teams[y] = new BowlingTeam(); System.out.print("Enter team name >> "); name = input.nextLine(); teams[y].setTeamName(name); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) { System.out.print("Enter team member's name >> "); name = input.nextLine(); teams[y].setMember(x, name); } } for(y = 0; y < NUM_TEAMS; ++y) { System.out.println("\nMembers of team " + teams[y].getTeamName()); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) System.out.print(teams[y].getMember(x) + " "); System.out.println(); } } }
    import java.util.*; public class BowlingTeamDemo3 { public static void main(String[] args) { String name; final int NUM_TEAMS = 4; BowlingTeam[] teams = new BowlingTeam[NUM_TEAMS]; int x; int y; final int NUM_TEAM_MEMBERS = 4; Scanner input = new Scanner(System.in); for(y = 0; y < NUM_TEAMS; ++y) { teams[y] = new BowlingTeam(); System.out.print("Enter team name >> "); name = input.nextLine(); teams[y].setTeamName(name); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) { System.out.print("Enter team member's name >> "); name = input.nextLine(); teams[y].setMember(x, name); } } for(y = 0; y < NUM_TEAMS; ++y) { System.out.println("\nMembers of team " + teams[y].getTeamName()); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) System.out.print(teams[y].getMember(x) + " "); System.out.println(); } System.out.print("\n\nEnter a team name to see its roster >> "); name = input.nextLine(); for(y = 0; y < teams.length; ++y) if(name.equals(teams[y].getTeamName())) for(x = 0; x < NUM_TEAM_MEMBERS; ++x) System.out.print(teams[y].getMember(x) + " "); System.out.println(); } }
    import java.util.*; public class BowlingTeamDemo4 { public static void main(String[] args) { String name; final int NUM_TEAMS = 4; BowlingTeam[] teams = new BowlingTeam[NUM_TEAMS]; int x; int y; final int NUM_TEAM_MEMBERS = 4; Scanner input = new Scanner(System.in); getTeamData(teams); for(y = 0; y < NUM_TEAMS; ++y) { System.out.println("\nMembers of team " + teams[y].getTeamName()); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) System.out.print(teams[y].getMember(x) + " "); System.out.println(); } System.out.print("\n\nEnter a team name to see its roster >> "); name = input.nextLine(); for(y = 0; y < teams.length; ++y) if(name.equals(teams[y].getTeamName())) for(x = 0; x < NUM_TEAM_MEMBERS; ++x) System.out.print(teams[y].getMember(x) + " "); System.out.println(); } public static void getTeamData(BowlingTeam[] teams) { String name; final int NUM_TEAMS = 4; int x; int y; final int NUM_TEAM_MEMBERS = 4; Scanner input = new Scanner(System.in); for(y = 0; y < NUM_TEAMS; ++y) { teams[y] = new BowlingTeam(); System.out.print("Enter team name >> "); name = input.nextLine(); teams[y].setTeamName(name); for(x = 0; x < NUM_TEAM_MEMBERS; ++x) { System.out.print("Enter team member's name >> "); name = input.nextLine(); teams[y].setMember(x, name); } } } }
  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; public final static int EVENT_NUM_LENGTH = 4; public final static String[] EVENT_TYPES = {"wedding", "baptism", "birthday", "corporate", "other"}; private String eventNumber; private int guests; private double pricePerGuest; private double priceForEvent; private String contactPhone; private int eventType; public Event() { this("A000", 0); } public Event(String num, int guests) { setEventNumber(num); setGuests(guests); } public void setEventNumber(String num) { boolean numOk = true; if(num.length() != EVENT_NUM_LENGTH || !Character.isLetter(num.charAt(0)) || !Character.isDigit(num.charAt(1)) || !Character.isDigit(num.charAt(2)) || !Character.isDigit(num.charAt(3))) eventNumber = "A000"; else eventNumber = num.toUpperCase(); } 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 String getContactPhone() { String phone; phone = "(" + contactPhone.substring(0, 3) + ") " + contactPhone.substring(3, 6) + "-" + contactPhone.substring(6, 10); return phone; } public void setContactPhone(String phone) { final int VALID_LEN = 10; final String INVALID_PHONE = "0000000000"; contactPhone = ""; int len = phone.length(); for(int x = 0; x < len; ++x) { if(Character.isDigit(phone.charAt(x))) contactPhone += phone.charAt(x); } if(contactPhone.length() != VALID_LEN) contactPhone = INVALID_PHONE; } public void setEventType(int code) { if(code < EVENT_TYPES.length) eventType = code; else eventType = EVENT_TYPES.length - 1; } public int getEventType() { return eventType; } public String getEventTypeString() { return EVENT_TYPES[eventType]; } 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; Event[] events = new Event[3]; int x; for(x = 0; x < events.length; ++x) { eventNum = getEventNumber(); guests = getGuests(); events[x] = new Event(eventNum, guests); events[x].setContactPhone(getPhone()); events[x].setEventType(getType()); } for(x = 0; x < events.length; ++x) { displayDetails(events[x]); } } public static String getEventNumber() { String num; Scanner input = new Scanner(System.in); System.out.print("\nEnter 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 int getType() { int eType; Scanner input = new Scanner(System.in); System.out.println("Event types are"); for(int x = 0; x < Event.EVENT_TYPES.length; ++x) System.out.println(" " + x + " " + Event.EVENT_TYPES[x]); System.out.print("Enter event type >> "); eType = input.nextInt(); return eType; } 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)); System.out.println("Contact phone number is: " + e.getContactPhone()); System.out.println("The event is type " + e.getEventType() + " which is the following type: " + e.getEventTypeString()); } public static Event getLarger(Event e1, Event e2) { Event larger = e2; if(e1.getGuests() >= e2.getGuests()) larger = e1; return larger; } public static String getPhone() { String phone; Scanner input = new Scanner(System.in); System.out.print("Enter contact phone number >> "); phone = input.nextLine(); return phone; } }
    class Rental { public static final int MINUTES_IN_HOUR = 60; public static final int HOUR_RATE = 40; public static final int CONTRACT_NUM_LENGTH = 4; public static final String[] EQUIP_TYPES = {"personal watercraft", "pontoon boat", "rowboat", "canoe", "kayak", "beach chair", "umbrella", "other"}; private String contractNumber; private int hours; private int extraMinutes; private double price; private String contactPhone; private int equipType; public Rental(String num, int minutes) { setContractNumber(num); setHoursAndMinutes(minutes); } public Rental() { this("A000", 0); } public void setContractNumber(String num) { boolean numOk = true; if(num.length() != CONTRACT_NUM_LENGTH || !Character.isLetter(num.charAt(0)) || !Character.isDigit(num.charAt(1)) || !Character.isDigit(num.charAt(2)) || !Character.isDigit(num.charAt(3))) contractNumber = "A000"; else contractNumber = num.toUpperCase(); } 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; } public String getContactPhone() { String phone; phone = "(" + contactPhone.substring(0, 3) + ") " + contactPhone.substring(3, 6) + "-" + contactPhone.substring(6, 10); return phone; } public void setContactPhone(String phone) { final int VALID_LEN = 10; final String INVALID_PHONE = "0000000000"; contactPhone = ""; int len = phone.length(); for(int x = 0; x < len; ++x) { if(Character.isDigit(phone.charAt(x))) contactPhone += phone.charAt(x); } if(contactPhone.length() != VALID_LEN) contactPhone = INVALID_PHONE; } public void setEquipType(int eType) { if(eType < EQUIP_TYPES.length) equipType = eType; else equipType = EQUIP_TYPES.length - 1; } public int getEquipType() { return equipType; } public String getEquipTypeString() { return EQUIP_TYPES[equipType]; } }
    import java.util.Scanner; public class RentalDemo { public static void main(String[] args) { String contractNum; int minutes; Rental[] rentals = new Rental[3]; int x; for(x = 0; x < rentals.length; ++x) { contractNum = getContractNumber(); minutes = getMinutes(); rentals[x] = new Rental(contractNum, minutes); rentals[x].setContactPhone(getPhone()); rentals[x].setEquipType(getType()); } for(x = 0; x < rentals.length; ++x) displayDetails(rentals[x]); } public static String getContractNumber() { String num; Scanner input = new Scanner(System.in); System.out.print("\nEnter 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 int getType() { int eType; Scanner input = new Scanner(System.in); System.out.println("Equipment types:"); for(int x = 0; x < Rental.EQUIP_TYPES.length; ++x) System.out.println(" " + x + " " + Rental.EQUIP_TYPES[x]); System.out.print("Enter equipment type >> "); eType = input.nextInt(); return eType; } 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,\n at a rate of $" + r.HOUR_RATE + " per hour and $1 per minute,\n the price is $" + r.getPrice()); System.out.println("Contact phone number is: " + r.getContactPhone()); System.out.println("Equipment rented is type #" + r.getEquipType() + " " + r.getEquipTypeString()); } 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; } public static String getPhone() { String phone; Scanner input = new Scanner(System.in); System.out.print("Enter contact phone number >> "); phone = input.nextLine(); return phone; } }