← All AP Java lessons

AP Java / J07

Arrays

Declaring arrays, passing arrays to methods, two-dimensional arrays, and applied assignments.

Java - Ch. 7 - Arrays - Assignments

7. Arrays

7.1 Overview

7.2 Declaring an Array

7.3 Passing an array to a method

7.4 2D Arrays

Chapter 7: Assignments

A7.1 Getting going with arrays

A7.2 Largest number in an array

A7.3 Reverse an array

A7.4 Random array of numbers

A7.5 Averaging grades

A7.6 Printing a 2D array

A7.7 Class Averages

A7.8 Passing an Array to a Method

A7.9 Focusing on the ones

Projects

Project 7.1 Hangman

7. Arrays

7.1 Overview

EXAMPLE: x is declared as an array of integers and given 6 values to hold:

int[ ] x = {3, 55, 11, 7, 90, 4};

There are 6 values in the x array. Each of their positions have an index starting with zero:

The value of x[0] is 3 - This is element zero

The value of x[1] is 55 - This is element one

The value of x[2] is 11 - This is element two

The value of x[3] is 7 - This is element three

The value of x[4] is 90 - This is element four

The value of x[5] is 4 - This is element five

Important notes:

  1. While there are six values, the highest index is 5. The indexes go from 0 to 5.
  2. To find the length of the array, we use x.length. This would be 6.

Looping through the array above:

int x[ ] = {3, 55, 11, 7, 90, 4};

int sum = 0;

for (int i=0; i < x.length; i++)

{

sum = sum + x[i];

}

System.out.print(sum); // Prints 170, which is the sum of the

numbers in the array.

7.2 Declaring an Array

String[ ] names = {“zebra”, “mouse”, “chicken”};

int[ ] nums = new int[4];

double[ ] numList = new double[2];

numList[0] = 3.14;

numList[1] = 2.71828;

String names[ ] instead of String[ ] names

int nums[ ] instead of int[ ] nums

double numList[ ] instead of double[ ] numList

int - 0

double - 0.0

boolean - false

String - This is referred to as “null” when there is no memory address for

an object because the object has not yet been created.

7.3 Passing an array to a method

EXAMPLE: If we had an array of integers called nums, we could declare and initialize it like we have been. We could then send the entire thing to a method that would add all of the values and return the result. The program would look like this:

public class test1

{

public static void main (String[ ] args)

{

int nums[ ] = {1, 2, 3, 4, 100};

System.out.print( add(nums) );

}

// The part of the array header in the parentheses tells me that add needs // to be handed an array of integers which will be called x while in the

// method.

public static int add(int[ ] x)

{

int total = 0;

for (int i = 0; i < x.length; i++)

{

total += x[i];

}

return total;

}

}

7.4 2D Arrays

5 10 15

1 2 3

as an array of arrays. If we had the following two arrays:

int[ ] array1 = {5, 10, 15}; // Represents the top row

int[ ] array2 = {1, 2, 3}; // Represent the bottom row

we could store all of these values in a 2D array like this:

int[ ][ ] masterArray = { {5, 10, 15} , {1, 2, 3} };

The first array, array1, has become the first element in our 2D array, masterArray. The

second array, array2, has become our second element of masterArray.

Some sample values from masterArray would look like this:

masterArray[0][2] = 15;

masterArray[1][0] = 1;

This becomes a perfect fit for using nested loops where the outer loop represents the

row and the inner loop represents the column (and the actual value).

Chapter 7: Assignments

A7.1 Getting going with arrays

Create a program that populates an array with five Strings and then prints out the values using a loop.

PROGRAM STRUCTURE:

// Declare and initialize an array with five Strings

// Use the examples above for a general outline of structure

//for loop

{

// Print the value of each element based on the counter in the for loop

}

SAMPLE OUTPUT:

House

Car

Agony

Another String

Cantaloupe

A7.2 Largest number in an array

Write a program that takes an array of three integers from user input and determines which one is the largest.

PROGRAM STRUCTURE:

// Declare an integer array and ask the user for three positive integers

// Declare a variable highest with an initial value of 0 that will hold the largest

value

//for loop

{

// Compare each value of the array to the highest variable.

// If the value is higher, replace the value of highest with that value.

}

// Print the value of highest.

SAMPLE OUTPUT:

Please give me a number:

8

Another:

10

Another:

1

The highest number that you gave me was 10.

A7.3 Reverse an array

Hard-code a five-element array. Print the values out in reverse order.

PROGRAM STRUCTURE:

// Create an integer array of 5 numbers (example: [2, 4, 6, 8, 10])

//for loop

{

// Print each value starting with the last one and working your way back

}

SAMPLE OUTPUT:

10 8 6 4 2

A7.4 Random array of numbers

Create an array with 10 random numbers from 1 to 100. Print the array to the screen. Ask the user for a number. Check to see if that number is in the array and report back the result. Ask the user for another number.

PROGRAM STRUCTURE:

// You are on your own!

SAMPLE RUN:

Random array: [33, 5, 67, 80, 34, 12, 2, 95, 77, 4]

Which number would you like to check for?

12

That number is in the array.

Which number would you like to check for?

85

That number is not in the array.

Which number would you like to check for?

…...

A7.5 Averaging grades

Create three integer arrays that each hold four grades called student1, student2, and student3. Hard-code each of them with their four grades. Pass each array to a method that will find the average for each student and print out the results.

PROGRAM STRUCTURE:

// You are on your own.

SAMPLE OUTPUT:

Student #1 has an average of 77.

Student #2 has an average of 90.

Student #3 has an average of 74.

A7.6 Printing a 2D array

Create a two-dimensional array that has the following hard-coded values:

2 4 6 8

1 3 5 9

10 20 30 40

You can create these values using the following format which is valid in Java. Try to understand how there are three rows defined with four values in each:

int nums[ ][ ] = { {2, 4, 6, 8}, {1, 3, 5, 9}, {10, 20, 30, 40} };

Print out the values of the array using a nested loop. The outer loop will count the rows and the inner loop will count the columns. To find the number of rows, use nums.length. In this example, it would return 3. To find the number of columns, use nums[0].length. In this example, it would return 4.

Also, sum the numbers and print the total at the end.

OUTPUT:

2 4 6 8

1 3 5 9

10 20 30 40

Total of all values: 138

A7.7 Class Averages

Create a 2D array that is 3 x 2. This will represent three different tests with two grades for each test. Populate the array with user input. Using a loop, print out the average of each test.

SAMPLE OUTPUT:

Enter the first grade for the first test:

80

Enter the second grade for the first test:

70

Enter the first grade for the second test:

100

Enter the second grade for the second test:

90

Enter the first grade for the third test:

60

Enter the second grade for the third test:

60

The averages of the tests are:

Test #1: 75

Test #2: 95

Test #3: 60

A7.8 Passing an Array to a Method

Create a program that passes a 3x5 boolean array (hard-coded) to a method. The method should count how many “true” values are in the array and return that value, an integer.

SAMPLE OUTPUT:

There are 7 true values in the array.

A7.9 Focusing on the ones

Create a 2D array that is 4 x 5 and is filled with randomly generated integers from 1 to 20 inclusive. This will involve a nested loop. Using a second nested loop, print the entire array in a 4 x 5 grid and have it report how many of each number ends in 1, 2, 3, 4…. Efficiency counts here. Don’t use ten if statements.

SAMPLE OUTPUT:

1 5 19 18 6

11 15 11 20 2

4 4 17 12 9

2 1 16 17 4

There are 4 numbers that end in 1.

There are 3 numbers that end in 2.

There are 0 numbers that end in 3.

There are 3 numbers that end in 4.

There are 2 numbers that end in 5.

There are 2 numbers that end in 6.

There are 2 numbers that end in 7.

There are 1 numbers that end in 8.

There are 2 numbers that end in 9.

There are 1 numbers that end in 0.

Projects

Project 7.1 Hangman

In this program, the computer is playing the game and you enter the word that it has to guess.

Main Arrays:

For the example where the word entered by the user is “bread” and “r”, “z” and “d” have already been guessed:

theAlphabet: [a, b, c, …….x, y, z]

alreadyGuessed: [*, *, *, d, *, *, ……*, *, z]

actualWord: [b, r, e, a, d]

computersWord: [*, r, *, *, d]

Method descriptions:

Method #1: main method - This method is where it all starts. It runs the game. It should call all other methods where appropriate.

Method #2: newLetter - This method should return a letter that has not yet been guessed which should be called “guessedLetter”. There should be an array of letters that have been guessed called “alreadyGuessed” that is referenced for each new letter generated and after a letter has been guessed, it should be added to that array

Signature: String newLetter(String[ ] alreadyGuessed, String[ ] theAlphabet)

Method #3: displayStatus - This method should show how close the computer is to getting the actual word. It should also show which letters have been guessed already. It can also show the hangman picture.

Signature: void displayStatus(String[ ] actualWord, String[ ] computersWord, String guessedLetter)

Method #4: compWord - This method should compare the guessed letter to the actualWord array and populate the array that holds the computer’s version of the actualWord array that it has already figured out.

Signature: void compWord(String[ ] actualWord, String[ ] computersWord,

String guessedLetter)

SAMPLE OUTPUT:

Please enter a word for the computer to guess: bread

Guess #1: s

Solved word: - - - - -

Guessed letters: s

Guess #2: r

Solved word: - r - - -

Guessed letters: s r

Guess #3: d

Solved word: - r - - d

Guessed letters: s r d