Java Reference
In-Depth Information
Sample Run: (In this sample run, the user input is shaded.)
Enter the radius of circle 1: 7
Enter the radius of circle 2: 4
Enter the radius of circle 3: 8
Enter the radius of circle 4: 9
Enter the radius of circle 5: 6
Circle 1: Radius = 7.00, Perimeter = 43.98, Area = 69.09
Circle 2: Radius = 4.00, Perimeter = 25.13, Area = 39.48
Circle 3: Radius = 8.00, Perimeter = 50.27, Area = 78.96
Circle 4: Radius = 9.00, Perimeter = 56.55, Area = 88.83
Circle 5: Radius = 6.00, Perimeter = 37.70, Area = 59.22
The preceding program works as follows. The statement in Line 7 creates the array
circles
of 5
Circle
objects. The
for
loop in Line 9 prompts the user to enter the
radius of 5 circles (Line 11), inputs the radius of each circle (Line 12), and instantiates and
sets the radius of circles (Line 13). The
for
loop in Line 16 outputs the radius, perimeter,
and area of each circle. Note that in the
class
Circle
, the
toString
method returns
the radius, perimeter, and area of a circle.
9
EXAMPLE 9-9
In Chapter 8, we created the
class
RollDie
to roll a die. The following program uses
this class to roll 100 dice and outputs the number of times each number is rolled, the
number(s) that are rolled the maximum number of times, and the maximum roll count.
// This program rolls 100 dice. It outputs the number of times
// each number is rolled, the number(s) that are rolled the
// maximum number of times, and the maximum roll count.
import
java.util.*;
//Line 1
public class
TestProgArrayofDice
//Line 2
{
//Line 3
static
Scanner console =
new
Scanner(System.in);
//Line 4
public static void
main(String[] args)
//Line 5
{
//Line 6
RollDie[] dice =
new
RollDie[100];
//Line 7
int
[] rollCount =
new int
[6];
//Line 8
int
maxNumRoll = 0;
//Line 9
for
(
int
i = 0; i < 100; i++)
//Line 10
Search WWH ::
Custom Search