Multi-dimensional Arrays

advertisement
• An array can be sent as a parameter to a class, as
well as returned to a client
in a class:
public String[ ] ned (String[ ] stark)
{
stark[2] = “bran”;
return stark;
}
in a client:
stark = objectName.ned(stark); // assume an array called stark
• To find the mode from the elements of an
array, first you must determine the
frequency of each number occurring….
– Demo: ArrayFrequencyDemo
•
Create a class called ArrayClass. Write 2
methods:
1. setArray( ) receives an int parameter from the client
called size, creates an array of integers with that size,
then populates the array by asking the user for values.
Error check: Maximum value of each array element =
100.
(“Enter value #6 (max = 100):”),
then returns the array to the client.
2. getMode( ) receives the array as a parameter, then goes
through the values in the array and returns the mode
•
Then create a client, ArrayClient, that tests these
2 methods. Start by asking the user how many
values they have to enter.
2-dimensional Arrays
• A 2-dimensional array has rows and columns
• It is actually an “array of arrays”
• A Tic-Tac-Toe board is an example of a 3 by 3
2-d array
• Syntax:
type[][] name = new type[rows][columns]
• A loop inside a loop is called a nested loop
• Almost always, we use nested for-loops to process
through a 2-d array
• Demo2dArray
As Parameters
• 2-d arrays can be passed as a parameter or
returned from a method
• Syntax:
public void setBoard(String[][] ticTacToe)
// receives a 2-d array as a parameter
or…
public String[][] getBoard( )
// this method would return a 2-d array to the client
Assignment #1 (Classroom)
• Create a classroom diagram: 5 rows, 6 columns.
• Place a dash in each “box.”
• There are 12 students in the class. Ask the user
where each student wants to sit, and then place an
‘s’ in that spot.
• After each student is placed, display the classroom.
• Error checking:
– Don’t allow the user to choose a spot that’s already
taken.
– Prevent OutOfBounds exceptions
Assignment #2 (Connect3)
• You know the game Connect 4. Create a
version of this game called Connect 3: it
uses a 3 by 4 table, and the first player to
connect 3 in a row (horizontal, vertical, or
diagonal) wins.
• Remember, it is a 2-player game, and each
player chooses a column to drop a piece
into. “Gravity” pulls each piece to the
lowest spot available.
• Allow the user to play multiple times if they
want to.
Download
Related flashcards
Create Flashcards