Java Chapter 7

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

An array of ints, arr, has been declared and initialized. Write the statements needed to reverse the elements in the array. So, if the elements were originally 5, 13, 4, 97 then after your code executes they would be 97, 4, 13, 5.

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

Write the definition of a method named sumArray that has one parameter, an array of ints. 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;}

Declare and instantiate a 3x3 two-dimensional array of integers named tictactoe

int tictactoe[] []= new int [3][3];

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 true if the elements of the first column are all equal.

tictactoe[0][0] == tictactoe[1][0] && tictactoe[1][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 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 that of the first element in the last row.

tictactoe[2][0]

Assume that the ArrayList 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.get(arr.size()-2);

Declare and instantiate an array named scores of twenty-five elements of type int.

int[] scores = new int[25];

Declare a two-dimensional array of strings named chessboard.

String chessboard[][];

Given an ArrayList a, write an expression that refers to the first element of the ArrayList.

a.get(0);

Assume that an ArrayList of integers named a has been declared and initialized. Write a single statement that assigns a new value to the first element of the ArrayList. The new value should be equal to twice the value stored in the last element of the ArrayList

a.set(0, a.get(a.size()-1)*2);

Given that an ArrayList named a with elements of type Integer has been declared, assign 3 to its first element.

a.set(0,3);

Given that an ArrayList of Integerss named a with 30 elements has been declared, assign 5 to its last element.

a.set(a.size()-1, 5);

Given that an ArrayList named a whose elements are of type Integer has been declared, assign the value -1 to the last element in a

a.set(a.size()-1,-1);

An ArrayList of Integers 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 the element at k

a.set(k-1,22);

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, has been created and assigned to a2d. Write an expression whose value is the number of elements in the first row. (Assume the array is not empty.)

a2d[0].length

Given an array a, write an expression that refers to the first element of the array

a[0]

Given that an array named a with elements of type int has been declared, assign 3 to its first element.

a[0] = 3;

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]

Given that an array of ints named a with 30 elements has been declared, assign 5 to its last element.

a[a.length-1] = 5;

Assume that an array of ints 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] ;

An array of ints 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 ints 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;

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 [] []={{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};

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];

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; k<zipcodeList.length-1; k++){if (zipcodeList[k]==zipcodeList[k+1]){duplicates=true;break;}}

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;

Declare a multidimensional array of ints, westboundHollandTunnelTraffic that can store the number of vehicles going westbound through the Holland Tunnel on a particular hour on a particular day on a particular week on a particular year. The innermost dimension should be years, with the next being weeks, and so on

int westboundHollandTunnelTraffic [ ] [ ] [ ] [ ];

In a single statement: declare, create and initialize an array named a of ten elements of type int with the values of the elements (starting with the first) set to 10, 20, ..., 100 respectively.

int[] a = {10,20,30,40,50,60,70,80,90,100};

Write a statement to declare and initialize an array named denominations that contains exactly six elements of type of int.Your declaration statement should initialize the elements of the array to the following values: 1, 5, 10, 25, 50, 100. (The value 1 goes into the first element, the value 100 to the last.)

int[] denominations = {1,5,10,25,50,100};

Declare, create, and initialize a three-dimensional array of ints, x, that has 3 rows, each of which has 2 columns where each column is an array 4 ints. The elements in the first row are all 5, in the second row are all 7, and in the third row the first column is all 8 and the second column is 30, 31, 32, and 33

int[][][] x = {{{5,5,5,5},{5,5,5,5}},{{7,7,7,7},{7,7,7,7}},{{8,8,8,8},{30,31,32,33}}};

Assume you are given a boolean variable named isSquare and a 2-dimensional array that has has been created and assigned to a2d. Write some statements that assign true to isSquare if the entire 2-dimensional array is square meaning every row and column has the same number of elements as every other row and column.

isSquare = true ; for (int i = 0 ; i < a2d.length; i++ ) {if (a2d.length != a2d[i].length ) {isSquare = false ;} }

Assume you are given an int variable named nElements and a 2-dimensional array that has been created and assigned to a2d. Write one or more statements that assign to nElements the total number of elements that could be stored in the entire 2-dimensional array.

nElements=0;for (int i=0; i<a2d.length; i++)nElements += a2d[i].length;

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++;

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.

numberOfIncompletes = 0;for(k=0; k < incompletes.length; k++){if (studentID == incompletes[k])numberOfIncompletes++;}

printArray is a method that accepts one argument, an array of ints. The method prints the contents of the array; it does not return a value. inventory is an array of ints 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 a static method, getBigWords, that gets a single String parameter and returns an array whose elements are the words in the parameter that contain more than 5 letters. (A word is defined as a contiguous sequence of letters.) EXAMPLE: So, if the String argument passed to the method was "There are 87,000,000 people in Canada", getBigWords would return an array of two elements, "people" and "Canada". ANOTHER EXAMPLE: If the String argument passed to the method was "Send the request to [email protected]", getBigWords would return an array of three elements, "request", "support" and "turingscraft".

public static String[] getBigWords(String sentence) { int totalbigWords, currentWordStart, currentWordEnd, pointer; totalbigWords = currentWordStart = currentWordEnd = pointer = 0; while ((pointer != sentence.length() - 1) && (!sentence.isEmpty())) { if(Character.isLetter(sentence.charAt(pointer))) { currentWordStart = pointer; while ((Character.isLetter(sentence.charAt(pointer))) && (pointer < sentence.length() - 1)) { pointer++; } currentWordEnd = pointer; if (currentWordEnd == sentence.length() - 1) currentWordEnd++; if (currentWordEnd == 0) currentWordEnd++; if (currentWordEnd - currentWordStart > 5) { totalbigWords++; currentWordStart = currentWordEnd = pointer; } } else pointer++; } String[] bigWords = new String[totalbigWords]; totalbigWords = currentWordStart = currentWordEnd = pointer = 0; while (pointer < sentence.length() - 1) { if(Character.isLetter(sentence.charAt(pointer))) { currentWordStart = pointer; while ((Character.isLetter(sentence.charAt(pointer))) && (pointer < sentence.length() - 1 )) { pointer++; } currentWordEnd = pointer; if (currentWordEnd == 0) currentWordEnd++; if (currentWordEnd == sentence.length() - 1) currentWordEnd++; if (currentWordEnd - currentWordStart > 5) { bigWords[totalbigWords] = sentence.substring(currentWordStart, currentWordEnd); totalbigWords++; currentWordStart = currentWordEnd = pointer; } } else pointer++; } return bigWords;}

Assume the existence of a Widget class that implements the Comparable interface and thus has a compareTo method that accepts an Object parameter and returns an int. Write an efficient static method, getWidgetMatch, that has two parameters. The first parameter is a reference to a Widget object. The second parameter is a potentially very large array of Widget objects that has been sorted in ascending order based on the Widget compareTo method. The getWidgetMatch searches for an element in the array that matches the first parameter on the basis of the equals method and returns true if found and false otherwise

public static boolean getWidgetMatch(Widget widget, Widget[] widArr) { int first = 0; int last = widArr.length - 1; while (first <= last) { int middle = (first + last) / 2; if (widArr[middle].equals(widget)) return true; if (widArr[middle].compareTo(widget) < 0) first = middle + 1; else last = middle - 1; } return false;}

Write a 'main' method that examines its command-line arguments and calls the (static) method displayHelp if the only argument is the class name. Note that displayHelp accepts no parameters otherwise, 'main' calls the (static) method argsError if the number of arguments is less than four. argsError accepts the number of arguments (an integer) as its parameter otherwise, 'main' calls the (static) method processArgs, which accepts the command-line argument array as its parameter.

public static void main(String[] args) { if(args.length==1){ displayHelp(); }else if(args.length < 4){ argsError(args.length); }else{ processArgs(args); } }

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.

public void reverse(int[] a) {int tmp;for(int i = 0, j = a.length - 1; i < a.length / 2; i++, j--) {tmp = a[i];a[i] = a[j];a[j] = tmp;}}

Assume that an ArrayList of Integers named salarySteps that contains exactly five elements has been declared and initialized. Write a statement that assigns the value 160000 to the last element of the ArrayList salarySteps.

salarySteps.set(salarySteps.size()-1, 160000);

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 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];

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]

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];}

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];

Write a RainFall class that has the following field:• an array of doubles that stores the rainfall for each of the 12 months ofthe year (where the first index corresponds with January, the second withFebruary, etc.)The class should also have the following methods:• a method that returns the total rainfall for the entire year• a method that returns the average monthly rainfall for the year• a method that returns the month with the most rain as a string• a method that returns the month with the least rain as a stringDemonstrate the class in a program that takes 12 doubles from the user (take thedoubles in the order of the months of the year, the first corresponding to therainfall in January, etc.). Do input validation: if the user inputs a negativenumber, ignore it and continue asking them for input until you have 12nonnegative doubles.Once the user has given you all 12 doubles, create an instance of the RainFallclass and call its methods, printing out the total rainfall, the averagemonthly rainfall, the month with the most rain, and the month with the leastrain, each on a separate line.

*

Write a method f that accepts an ArrayList containing String objects. The method should return a String containing the first character of each string in the ArrayList, in the order in which they appear. Thus, if the ArrayList contains the Strings: Hello world goodbye the return value of the method would be the String Hwg

*

Suppose v is an array with 100 int elements. If 100 is assigned to v[100], what happens?

An exception will be thrown when that statement is executed.

Declare an ArrayList 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.

ArrayList taxRates = new ArrayList();taxRates.add(0.10);taxRates.add(0.15);taxRates.add(0.21);taxRates.add(0.28);taxRates.add(0.31);


Ensembles d'études connexes

BIOL 2401 Chapter 2 Module 4: 2.08-2.12

View Set

Why did south carolina secede from the Union

View Set

Milady capítulo 21 color parte A

View Set

MT-chapter 5 test review(body structure)

View Set

Chapter 9 Mastering Biology Study Module Q's

View Set

Corporate Finance MGMT 332 Chapter 1

View Set