Array Java Exercise

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

ARRAY

 Data structure – collection of related data items


 Arrays are data structures consisting of related data items of the same type
 An array is a group of variables (called elements or components) containing values that all
have the same type. Arrays are objects, so they’re considered reference types
 The position number of the element is called the element’s index or subscript.

 Declaring and Creating Arrays


 Array objects occupy space in memory.

int[] c = new int[ 12 ]; or

int[] c; // declare the array variable


c = new int[ 12 ]; // create the array; assign to array variable

Examples Using Arrays


Creating and Initializing an Array
public class InitArray
{
public static void main( String[] args )
{
int[] array; // declare array named array
array = new int[ 10 ]; // create the array object

System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings


// output each array element's value
for ( int counter = 0; counter < array.length; counter++ )
System.out. printf( "%5d%8d\n", counter, array[ counter ] );

} // end main

} // end class InitArray

Output :
Index Value
00
10
20
30
40
50
60
70
80
90

Using an Array Initializer


 array initializer—a comma-separated list of expressions (called an initializer list) enclosed
in bracesis identical to that in Fig. 7.2 (lines 15–16).

int[] n = { 10, 20, 30, 40, 50 };


Calculating the Values to Store in an Array
public class InitArray
{
public static void main( String[] args )
{
final int ARRAY_LENGTH = 10; // declare constant
int[] array = new int[ ARRAY_LENGTH ]; // create array

// calculate value for each array element


for ( int counter = 0; counter < array.length; counter++ )
array[ counter ] = 2 + 2 * counter;
System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings
// output each array element's value
for ( int counter = 0; counter < array.length; counter++ )
System.out.printf( "%5d%8d\n", counter, array[ counter ] );
} // end main
} // end class InitArray

Index Value
0 2
1 4
2 6
3 8
4 10
5 12
6 14
7 16
8 18
9 20
Summing the Elements of an Array

public class SumArray


{
public static void main( String[] args )
{
int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };
int total = 0;
// add each element's value to total

for ( int counter = 0; counter < array.length; counter++ )


total += array[ counter ];

System.out.printf( "Total of array elements: %d\n", total );


} // end main
} // end class SumArray
Total of array elements: 849

Using Bar Charts to Display Array Data Graphically

public class BarChart


{
public static void main( String[] args )
{
int[] array = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };
System.out.println( "Grade distribution:" );
// for each array element, output a bar of the chart
for ( int counter = 0; counter < array.length; counter++ )
{
// output bar label ( "00-09: ", ..., "90-99: ", "100: " )
if ( counter == 10 )
System.out.printf( "%5d: ", 100 );
else
System.out.printf( "%02d-%02d: ",counter * 10, counter *
10 + 9 );
// print bar of asterisks
for ( int stars = 0; stars < array[ counter ]; stars++ )
System.out.print

System.out.println(); // start a new line of output


} // end outer for
} // end main
} // end class BarChart
Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *

Using the Elements of an Array as Counters

import java.util.Random;
public class RollDie
{
public static void main( String[] args )
{
Random randomNumbers = new Random(); // random number generator
int[] frequency = new int[ 7 ]; // array of frequency counters
// roll die 6,000,000 times; use die value as frequency index
for ( int roll = 1; roll <= 6000000; roll++ )
++frequency[ 1 + randomNumbers.nextInt( 6 ) ];
System.out.printf( "%s%10s\n", "Face", "Frequency" );
// output each array element's value
for ( int face = 1; face < frequency.length; face++ )
System.out.printf( "%4d%10d\n", face, frequency[ face ]
);
} // end main
} // end class RollDie

Face Frequency
1 999690
2 999512
3 1000575
4 999815
5 999781
6 1000627

Using Arrays to Analyze Survey Results


Consider the following
problem statement:
Twenty students were asked to rate on a scale of 1 to 5 the quality of the food in the
student cafeteria, with 1 being “awful” and 5 being “excellent.” Place the 20 responses
in an integer array and determine the frequency of each rating.
public class StudentPoll
{
public static void main( String[] args )
{
// student response array (more typically, input at runtime)
int[] responses = { 1, 2, 5, 4, 3, 5, 2, 1, 3, 3, 1, 4, 3, 3,
3,2, 3, 3, 2, 14 };
int[] frequency = new int[ 6 ]; // array of frequency counters
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0; answer < responses.length; answer++ )
{
try
{
++frequency[ responses[ answer ] ];
} // end try
catch ( ArrayIndexOutOfBoundsException e )
{
System.out.println( e );
System.out.printf( " responses[%d] =
%d\n\n",answer, responses[ answer ] );
} // end catch
} // end for
System.out.printf( "%s%10s\n", "Rating", "Frequency" );
// output each array element's value
for ( int rating = 1; rating < frequency.length; rating++ )
System.out.printf( "%6d%10d\n", rating, frequency[ rating
] );
} // end main
} // end class StudentPoll

java.lang.ArrayIndexOutOfBoundsException: 14
responses[19] = 14
Rating Frequency
13
24
38
42
52

7.5 Case Study: Card Shuffling and Dealing Simulation


public class Card
{
private String face; // face of card ("Ace", "Deuce", ...)
private String suit; // suit of card ("Hearts", "Diamonds", ...)
// two-argument constructor initializes card's face and suit
public Card( String cardFace, String cardSuit )
{
face = cardFace; // initialize face of card
suit = cardSuit; // initialize suit of card
} // end two-argument Card constructor
// return String representation of Card
public String toString()
{
return face + " of " + suit;
} // end method toString
} // end class Card

import java.util.Random;
public class DeckOfCards
{

private Card[] deck; // array of Card objects


private int currentCard; // index of next Card to be dealt (0-51)
private static final int NUMBER_OF_CARDS = 52; // constant # of Cards
// random number generator
private static final Random randomNumbers = new Random();
// constructor fills deck of Cards
public DeckOfCards()
{
String[] faces = { "Ace", "Deuce", "Three", "Four", "Five", "Six”, "Seven", "Eight", "Nine", "Ten", "Jack",
"Queen", "King" };
String[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" };
deck = new Card[ NUMBER_OF_CARDS ]; // create array of Card objects
// populate deck with Card objects
for ( int count = 0; count < deck.length; count++ )
deck[ count ] = new Card( faces[ count % 13 ], suits[ count / 13 ] );
} // end DeckOfCards constructor
// shuffle deck of Cards with one-pass algorithm
public void shuffle()
{
// after shuffling, dealing should start at deck[ 0 ] again
currentCard = 0; // reinitialize currentCard
// for each Card, pick another random Card (0-51) and swap them
for ( int first = 0; first < deck.length; first++ )
{
// select a random number between 0 and 51
int second = randomNumbers.nextInt( NUMBER_OF_CARDS );
// swap current Card with randomly selected CarD
Card temp = deck[ first ];
deck[ first ] = deck[ second ];
deck[ second ] = temp;
}// end for
} // end method shuffle
// deal one Card
public Card dealCard()
{
// determine whether Cards remain to be dealt
if(currentCard < deck.length )
return deck[ currentCard++ ]; // return current Card in array
else
return null; // return null to indicate that all Cards were dealt
} // end method dealCard
} // end class DeckOfCards

You might also like