Вы находитесь на странице: 1из 24

Chapter 8 Arrays and Array list

8.1 Introduction to Arrays 20692 Declare an array named a of ten elements of type int and initialize the elements (starting with the first) to the values 10 , 20 , ..., 100 respectively. int[] a = {10,20,30,40,50,60,70,80,90,100}; 20693 Declare an array named taxRates of five elements of type double and initialize the elements (starting with the first) to the values 0.10 , 0.15 , 0.21 , 0.28 , 0.31 , respectively. double[] taxRates = {0.10, 0.15, 0.21, 0.28, 0.31}; 20759 Declare an array reference variable, week, and initialize it to an array containing the strings "mon", "tue", "wed", "thu", "fri", "sat", "sun" (in that order). String [] week = {"mon", "tue", "wed", "thu", "fri", "sat", "sun"}; 20690 Declare and instantiate an array named scores of twenty-five elements of type int . int[] scores = new int[25]; Write a statement that declares an array named streetAddress that contains exactly eighty elements of type char . char[] streetAddress = new char [80]; 8.2 Processing Array Elements Given Suppose the values of the array a BEFORE your code executed were: 15,7,22,4. Then, AFTER your code executed, the values of the array a would be: 3,7,22,4. Note that the value of the first element was changed to 3. that an array named a with elements of type int has been declared, assign 3 to its first element a[0] = 3;

Assume that an array named salarySteps whose elements are of type int and that has exactly five elements has already been declared. Write a single statement to assign the value 30000 to the first element of this array. salarySteps[0] = 30000;

Assume that an array of integers named salarySteps that contains exactly five elements has been declared. Write a statement that assigns the value 160000 to the last element of the array salarySteps . salarySteps[4] = 160000;

Assume that an array named a containing exactly 5 integers has been declared and initialized. Write a single statement that adds 10 to the value stored in the first element of the array a[0]+= 10;

Given that an array of int s named a with 30 elements has been declared, assign 5 to its last element. a[a.length-1] = 5;

Given that an array named a whose elements are of type int has been declared, assign the value -1 to the last element in a . a[a.length-1] = -1;

Assume that an array of int s named a has been declared with 12 elements. The integer variable k holds a value between 0 and 6 . Assign 15 to the array element whose index is k . a[k] = 15;

An array of int s named a has been declared with 12 elements. The integer variable k holds a value between 0 and 6 . Assign 9 to the element just after a[k] . a[k+1] = 9;

An array of int s named a has been declared with 12 elements. The integer variable k holds a value between 2 and 8 . Assign 22 to the element just before a[k] . a[k-1] = 22 ;

Assume that an array of integers named a has been declared and initialized. Write a single statement that assigns a new value to the first element of the array. The new value should be equal to twice the value stored in the last element of the array. a[0] = 2 * a[a.length-1] ;

Assume that an array of int s named a that contains exactly five elements has been declared and initialized. In addition, an int variable j has also been declared and initialized to a value somewhere between 0 and 3 . Write a single statement that assigns a new value to element of the array indexed by j . This new value should be equal to twice the value stored in the next element of the array (i.e. the element after the element indexed by j . a[j] = 2 * a[j+1] ; Given an array a , write an expression that refers to the first element of the array. A[0]

Given an array a , declared to contain 34 elements, write an expression that refers to the last element of the array. a[33]

Assume that the array arr has been declared. Write a statement that assigns the next to last element of the array to the variable x , which has already been declared. x=arr[arr.length-2];

Given that the array monthSales of integers has already been declared and that its elements contain sales data for the 12 months of the year in order (i.e., January, February, etc.), write a statement that writes to standard output the element corresponding to October. Do not write anything else out to standard output. System.out.print(monthSales[9]) System.out.println(); 8.3 passing arrays as arguments

printArray is a method that accepts one argument, an array of int s. The method prints the contents of the array; it does not return a value. inventory is an array of int s that has been already declared and filled with values. Write a statement that prints the contents of the array inventory by calling the method printArray . printArray(inventory); Write the definition of a method printArray , which has one parameter, an array of int s. The method does not return a value. The method prints out each element of the array, on a line by itself, in the order the elements appear in the array, and does not print anything else void printArray(int a[]) { int i; for (i=0;i<a.length;i++) { System.out.print(a[i]); System.out.println(); } }

Write the definition of a method named sumArray that has one parameter, an array of int s. The method returns the sum of the elements of the array as an int . int sumArray(int a[]) { int i,total=0; for(i=0;i<a.length;i++) total+=a[i]; return total; } Write the definition of a method, isReverse , whose two parameters are arrays of integers of equal size. The method returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in re boolean isReverse(int a[], int b[]) { int k; for (k=0; k<a.length && a[k]==b[a.length-1-k]; k++); return k==a.length; }

Write the definition of a method reverse , whose parameter is an array of integers. The method reverses the elements of the array. The method does not return a value. void reverse(int a[]) { int k, temp;

for (k=0; k<a.length/2; k++) { temp = a[k]; a[k] = a[a.length-1-k]; a[a.length-1-k] = temp; } }

8.4 some usefull Given an array of ints named x and an int variable named total that has already been declared, write some code that places the sum of all the elements of the array x into total. Declare any variables that you need. total = 0; for (int i=0; i<x.length; i++) total+=x[i]; Given an array temps of double s, containing temperature data, compute the average temperature. Store the average in a variable called avgTemp . Besides temps and avgTemp , you may use only two other variables -- an int variable k and a double variable named total , which have been declared. More... for (total=0.0, k=0; k<temps.length; k++) total += temps[k]; avgTemp = total/temps.length; We informally define the term corresponding element as follows: The first element in an array and the last element of the array are corresponding elements. Similarly, the second element and the element just before the last element are corresponding elements. The third element and the element just before the element just before the last element are corresponding elements -- and so on.

Given an array a, write an expression for the corresponding element of a[i]. a[a.length-1-i]

Reversing the elements of an array involves swapping the corresponding elements of the array: the first with the last, the second with the next to the last, and so on, all the way to the middle of the array. Given an array a and two other int variables, k and temp , write a loop that reverses the elements of the array. Do not use any other variables besides a , k , and temp . for (k=0;k<a.length/2;k++) { temp = a[k]; a[k] = a[a.length-1-k]; a[a.length-1-k] = temp; }

Given an int variable k , an int array incompletes that has been declared and initialized, an int variable studentID that has been initialized, and an int variable numberOfIncompletes , write code that counts the number of times the value of studentID appears in incompletes and assigns this value to numberOfIncompletes . You may use only k , incompletes , studentID , and numberOfIncompletes

or (numberOfIncompletes=0,k=0; k<incompletes.length; k++) if (incompletes[k] == studentID) numberOfIncompletes++;

Given the integer variables x and y , write a fragment of code that assigns the larger of x and y to another integer variable max . max = x; if (y > max) max = y; Write the definition of a method max that has three int parameters and returns the largest. public int max( int x , int y , int z ) { if (x>y&&x>z) { return x; } else if (y>x&&y>z) { return y; } else { return z; } }

An array of integers named parkingTickets has been declared and initialized to the number of parking tickets given out by the city police each day since the beginning of the current year. (Thus, the first element of the array contains the number of tickets given on January 1; the last element contains the number of tickets given today.) A variable named mostTickets has been declared, along with a variable k . Without using any additional variables, write some code that results in mostTickets containing the largest value found in parkingTickets . mostTickets = parkingTickets[0]; k = 1; while (k<parkingTickets.length) { if (mostTickets<parkingTickets[k]) mostTickets = parkingTickets[k]; k++; }

8.8 sequential search Given: an int variable k , an int array currentMembers that has been declared and initialized, an int variable memberID that has been initialized, and an boolean variable isAMember , write code that assigns true to isAMember if the value of memberID can be found in currentMembers , and that assigns false to isAMember otherwise. Use only k , currentMembers , memberID , and isAMember . for (k=0; k<currentMembers.length && memberID!=currentMembers[k]; k++); isAMember = k<currentMembers.length;

You are given an int variable k , an int array zipcodeList that has been declared and initialized, and an boolean variable duplicates . Write some code that assigns true to duplicates if there are two adjacent elements in the array that have the same value, and that assigns false to duplicates otherwise. Use only k , zipcodeList , and duplicates duplicates = false; for (k=0; !duplicates && k<zipcodeList.length-1; k++) if (zipcodeList[k] == zipcodeList[k+1]) duplicates = true;

You are given two int variables j and k , an int array zipcodeList that has been declared and initialized, and an boolean variable duplicates . Write some code that assigns true to duplicates if any two elements in the array have the same value, and that assigns false to duplicates otherwise. Use only j , k , zipcodeList , and duplicates duplicates = false; for (j=0; !duplicates && j<zipcodeList.length-1; j++) for (k=j+1; !duplicates && k<zipcodeList.length; k++) if (zipcodeList[k] == zipcodeList[j]) duplicates = true;

An array of Strings, names, has been declared and initialized. Write the statements needed to determine whether any of the the array elements are null or refer to the empty String. Set the variable hasEmpty to true if any elements are null or empty-- otherwise set it to false. hasEmpty = false; for (int i = 0; i < names.length; i++) if (names[i] == null || names[i].length() == 0) hasEmpty = true; 8.9 two dimensional arrays Declare a two-dimensional array of strings named chessboard. String [][] chessboard; Declare a two-dimensional array of integers named tictactoe. int [][] tictactoe; Declare and instantiate a 3x3 two-dimensional array of integers named tictactoe. int [][] tictactoe = new int[3][3] Assume that chessboard has been declared to be a two-dimensional array of strings. Write a statement that instantiates an 8x8 array of strings and assign it to chessboard. chessboard = new String[8][8]; Assume that tictactoe has been declared to be a two-dimensional array of integers. Write a statement that instantiates a 3x3 two-dimensional array of integers and assign it to tictactoe. tictactoe = new int[3][3]; Declare and create a two-dimensional array of chars, tictactoe, with 3 rows, each with 3 elements, and initialize it to all space characters. char[][] tictactoe = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}}; Declare and create a two-dimensional array of ints, plan, with 2 rows, and initialize the first row to 8, 20, 50 and the second row to 12, 30, 75. int[][] plan = { {8,20,50}, {12,30,75} };

A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is that of the first element in the first row. tictactoe[0][0] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is that of the last element in the first row. tictactoe[0][2] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is that of the first element in the last row. tictactoe[2][0] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is that of the middle element in the middle row. tictactoe[1][1] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of the first row are all equal. tictactoe[0][0] == tictactoe[0][1] && tictactoe[0][0] == tictactoe[0][2] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of the last row are all equal. tictactoe[2][0] == tictactoe[2][1] && tictactoe[2][0] == tictactoe[2][2] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of the first column are all equal. tictactoe[0][0] == tictactoe[1][0] && tictactoe[0][0] == tictactoe[2][0] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of the diagonal that includes the first element of the first row are all equal. tictactoe[0][0] == tictactoe[1][1] && tictactoe[0][0] == tictactoe[2][2] A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of the diagonal that does NOT include the first element of the first row are all equal. tictactoe[0][2] == tictactoe[1][1] && tictactoe[0][2] == tictactoe[2][0]

A 2-dimensional 3x3 array of ints, has been created and assigned to tictactoe. Write an expression whose value is true if the elements of any row or column or diagonal are equal. ictactoe[0][0] == tictactoe[0][1] && tictactoe[0][0] == tictactoe[0][2] || tictactoe[1][0] == tictactoe[1][1] && tictactoe[1][0] == tictactoe[1][2] || tictactoe[2][0] == tictactoe[2][1] && tictactoe[2][0] == tictactoe[2][2] || tictactoe[0][0] == tictactoe[1][0] && tictactoe[0][0] == tictactoe[2][0] || tictactoe[0][1] == tictactoe[1][1] && tictactoe[0][1] == tictactoe[2][1] || tictactoe[0][2] == tictactoe[1][2] && tictactoe[0][2] == tictactoe[2][2] || tictactoe[0][0] == tictactoe[1][1] && tictactoe[0][0] == tictactoe[2][2] || tictactoe[0][2] == tictactoe[1][1] && tictactoe[0][2] == tictactoe[2][0] A 2-dimensional array of ints, has been created and assigned to a2d. Write an expression whose value is the number of elements in the last row. (Assume the array is not empty.) a2d[a2d.length-1].length A 2-dimensional array of ints, has been created and assigned to a2d. Write an expression whose value is the number of rows in this array. a2d.length A 2-dimensional array of ints with 4 rows, has been created and assigned to a2d. Write an expression whose value is the total number of ints that could be stored in the entire array. a2d[0].length + a2d[1].length + a2d[2].length + a2d[3].length

Assume you are given a boolean variable named isRectangular and a 2-dimensional array that has has been created and assigned to a2d. Write some statements that assign true to isRectangular if the entire 2-dimensional array is rectangular, meaning every row has the same number of elements as every other row. isRectangular=true; for (int i=1; i<a2d.length && isRectangular; i++) if (a2d[i].length!=a2d[0].length) isRectangular = false; Assume you are given an int variable named nPositive and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the number of all the elements in the entire 2-dimensional array that are greater than zero and assign the value to nPositive. nPositive = 0; for (int i=0; i<a2d.length; i++) for (int j=0; j<a2d[i].length; j++) if (a2d[i][j] > 0) nPositive++; Assume you are given an int variable named sum and a 2-dimensional array of ints that has been created and assigned to a2d. Write some statements that compute the sum of all the elements in the entire 2-dimensional array and assign the value to sum. sum = 0; for (int i=0; i<a2d.length; i++) for (int j=0; j<a2d[i].length; j++) sum += a2d[i][j];

Given an array arr , of type int , along with two int variables i and j , write some code that swaps the values of arr[i] and arr[j] . Declare any additional variables as necessary. int temp; temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;

9,1 STATic class members Write the definition of a class Telephone . The class has no constructors, one instance variable of type String called number , and one static variable of type int called quantity . public class Telephone { private String number; private static int quantity; }

Write the definition of a class Telephone . The class has no constructors, one instance variable of type String called number , and two static variables. One is of type int called quantity , initialized to 250 ; the other is of type double called total , initialized to 15658.92 . public class Telephone { private String number; private static int quantity=250; private static double total=15658.92; } Write the definition of a class Telephone . The class has no constructors and one static method printNumber . The method accepts a String argument and prints it on the screen. The method returns nothing. public class Telephone { public static void printNumber(String s) { System.out.print(s); System.out.println(); }}

Write the definition of a class Telephone . The class has no constructors and one static method getFullNumber . The method accepts a String argument and returns it, adding 718- to the beginning of the argument. public class Telephone { public static String getFullNumber(String s) { return "718-"+s; } }

Write the definition of a class Telephone . The class has no constructors, one instance variable of type String called number , and two static variables. One is of type int called quantity ; the other is of type double called total . Besides that, the class has one static method makeFullNumber . The method accepts two arguments, a String containing a telephone number and an int containing an area code. The method concatenates the two arguments in the following manner: First comes the area code, then a dash, then the telephone number. The method returns the resultant string. public class Telephone { private String number; private static int quantity; private static double total;

public static String makeFullNumber(String s, int a) { return a+"-"+s; } }

There is often a limit on the number of open windows that can be maintained by the underlying system. Declare the variables maxOpenWindows and currentlyOpenWindows (both integer) which are to be part of the Window class. (These variables are static as, although associated with the Window class, they have nothing to do with any particular Window object). The variable maxOpenWindows should be initialized to 27, and the variable currentlyOpenWindows to 0 (in their declarations). Please submit the declarations of these two variables only-- nothing else static int maxOpenWindows = 27, currentlyOpenWindows; Provide the methods onOpen and onClose which are to be added to the Window class, and which would be called after a Window object is created and closed respectively. (The onOpen might be called from the constructor, while the onClose might be called after the user clicks some sort of 'close' or 'X' button.) static boolean onOpen() { if (currentlyOpenWindows >= maxOpenWindows) return false; currentlyOpenWindows++; return true; } static void onClose() {currentlyOpenWindows--;} 9.4 to the string method Assume the existence of a Window class with integer instance variables width, height, xPos and yPos. Define the method toString for the Window class. The String representation of a Window object should be of the form "A 'width'x'height' window at ('xPos','yPos')" where the values within the '''s are replaced by the actual values of the corresponding instance variables. For example, given a Window object whose widthpublic String toString() { return "A " + width + "x" + height + " window at (" + xPos + "," + yPos + ")"; } is 80, height is 20, xPos is 0 and yPos is 30, toString should return "A 80x20 window at (0,30)"

Define the method equals for the Window class. Two windows will be considered equal if they are the same size and at the same position public boolean equals(Window window) { return width == window.width && height == window.height && xPos == window.xPos && yPos == window.yPos; }

CH 10 TEXT PROCESSING AND MORE ABOUT WRAPPER CLASS Given the String variable str, write an expression that evaluates to the character at index 0 of str str.charAt(0) 10.3 more string methods

Given the String variable address , write an expression that returns the position of the first occurrence of the String "Avenue" in address . address.indexOf("Avenue") Assume that name is a variable of type String that has been assigned a value. Write an expression whose value is the second character of the value of name . So if the value of name were "Smith" the expression's value would be 'm'. name.charAt(1) Write an expression that whose value is the fifth character of the String name . name.charAt(4)

Assume that name is a variable of type String that has been assigned a value. Write an expression whose value is the last character of the value of name . So if the value of name were "Blair" the expression's value would be 'r'. name.charAt(name.length()-1)

Assume that word is a variable of type String that has been assigned a value. Write an expression whose value is a String consisting of the first three characters of the value of word . So if the value of word were "dystopia" the expression's value would be "dys". word.substring(0,3)

Assume that name is a variable of type String that has been assigned a value. Write an expression whose value is a String containing the second character of the value of name . So if the value of name were "Smith" the expression's value would be "m". name.substring(1,2)

Assume that word is a variable of type String that has been assigned a value. Write an expression whose value is a String consisting of the last three characters of the value of word . So if the value of word were "biggest" the expression's value would be "est". word.substring(word.length()-3,word.length())

Assume that sentence is a variable of type String that has been assigned a value. Assume furthermore that this value is a String consisting of words separated by single space characters with a period at the end. For example: "This is a possible value of sentence." Assume that there is another variable declared, firstWord , also of type String . Write the statements needed so that the first word of the value of sentence is assigned to firstWord . So, if the value of sentence were "Broccoli is delicious." your code would assign the value "Broccoli" to firstWord . firstWord = sentence.substring(0,sentence.indexOf(" "));

Assume that word is a variable of type String that has been assigned a value. Assume furthermore that this value always contains the letters "dr" followed by at least two other letters. For example: "undramatic", "dreck", "android", "no-drip". Assume that there is another variable declared, drWord , also of type String. Write the statements needed so that the 4-character substring word of the value of word starting with "dr" is assigned to drWord . So, if the value of word were "George slew the dragon" your code would assign the value "drag" to drWord . drWord = word.substring(word.indexOf("dr"), 4); Given a String variable named sentence that has been initialized, write an expression whose value is the index of the very last character in the String referred to by sentence . sentence.length()-1

Assume that s is a String . Write an expression whose value is true if and only if the value of s would come between "mortgage" and "mortuary" in the dictionary. "mortgage".compareTo(s)<= 0 && s.compareTo("mortuary")<0

Write a method, makeSubjectLine, that gets a String argument and returns the same String but with "Subject: " in front of it. So if the argument is "Are you going to the show?" the method returns "Subject: Are you going to the show?" String makeSubjectLine(String s) {return "Subject: " + s;} ite a method, getEmailUserName, that is passed a String argument that is an email address and returns the user-name part. So if "mozart@salzberg.de" is passed, the method returns "mozart". Assume that the argument will always be a correctly formatted email address. String getEmailUserName(String emailAddresss) {return emailAddresss.substring(0, emailAddresss.indexOf(" "));}

Write a method, getEmailDomain, that is passed a String argument that is an email address and returns the domain name part. So if "mozart@salzberg.de" is passed, the method returns "salzberg.de". Assume that the argument will always be a correctly formatted email address. String getEmailDomain(String emailAddresss) {return emailAddresss.substring(emailAddresss.indexOf(" ")+1);}

Write a method, makeEmailAddress, that is passed two String arguments: the first is a username, like "leadbelly" and the second is a domain name, like "blues.com". The method returns an email address formed from joining these with an "@": "leadbelly@blues.com". String makeEmailAddress(String username, String domainName) {return username + " " + domainName;}

Write a method, getFirstLine, that is passed a String argument and that returns the first line. (Recall that lines are terminated with the "\n" character.) Assume that the argument contains at least one complete, newline-terminated line. String getFirstLine(String lines) {return lines.substring(0, lines.indexOf("\n"));}

Write a method, getSecondLine, that is passed a String argument and that returns the second line, without its newline character. (Recall that lines are terminated with the "\n" character.) Assume that the argument contains at least two complete, newline-terminated lines. String getSecondLine(String lines) { int pos = lines.indexOf("\n"); lines = lines.substring(pos+1); return lines.substring(0, lines.indexOf("\n")); } Write a method, isEmailAddress, that is passed a String argument. It returns true or false depending on whether the argument has the form of an email address. In this exercise, assume that an email address has one and only one "@" sign and no spaces, tabs or newline characters. boolean isEmailAddress(String possibleEmailAddress) { boolean sawAt = false; for (int i = 0; i < possibleEmailAddress.length(); i++) { if (" \t\n".indexOf(possibleEmailAddress.charAt(i)) >= 0) return false; if (possibleEmailAddress.charAt(i) == ' ') { if (sawAt) return false; sawAt = true; } } return sawAt; }

A String variable, fullName, contains a name in one of two formats: last name, first name (comma followed by a blank), or first name last name (single blank) Extract the first name into the String variable firstName and the last name into the String variable lastName. Assume the variables have been declared and fullName already initialized. You may also declare any other necessary variables. nt pos = fullName.indexOf(","); if (pos >= 0) { lastName = fullName.substring(0, pos).trim(); firstName = fullName.substring(pos+1).trim(); } else { pos = fullName.indexOf(" "); firstName = fullName.substring(0, pos).trim(); lastName = fullName.substring(pos+1).trim(); } Given the String variables name1 and name2, write a fragment of code that assigns the larger of the two to the variable first (assume that all three are already declared and that name1 and name2 have been assigned values). (NOTE: "larger" here means alphabetically larger, not "longer". Thus, "mouse" is larger than "elephant" because "mouse" comes later in the dictionary than "elephant"!) first=name1; if(name2.compareTo(first)>0) first=name2;

Вам также может понравиться