Download Lecture Notes for Chapter 4 - Madison Area Technical College

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Computer Science Notes
Chapter 4
Page 1 of 21
Chapter 4: Loops
These notes are meant to accompany Introduction to Java Programming: Brief Version, seventh edition by Y.
Daniel Lang.
Programming Skills in a Nutshell:
At the end of this chapter you should have the following programming skills:
1. Use a while loop to repeat a block of code.
2. Use a do-while loop to repeat a block of code.
3. Use a for loop to repeat a block of code.
4. Be able to translate from one type of loop to the other.
5. Know the advantages of one type of loop over the other
6. Here is a template that uses the key programming skills you should have at this point:
import java.util.Scanner;
/**The Chap04Basics class implements an application that
* performs various mathematical tasks, and is meant to
* illustrate the basics of loop statements
* (i.e., while, do-while, and for loops).
* This is meant as an example of the material in Chapter 4 of the text
* _Introduction to Java Programming: Brief Version_, 7th ed. by Y. D. Liang
* @author Kevin Mirus
*/
public class Chap04Basics
{
/** Gives the user a menu of options of mathematical calculations.
* @param args is not used.
*/
public static void main(String[] args)
{
//Tell the user what the program does
System.out.println("This program will print the expansion of a " +
"binomial of the form (ax + by)^n.");
//Declare variables for the user input.
double a = 0., b = 0.;
int n = 0;
int repeatSentinel = 1;
Scanner keyboard = new Scanner(System.in);
//Embed the user input, computation, and output in a loop so that
//the user can do as many calculations as desired
//without having to re-start the program every time.
do
{
System.out.println("++++++++++++++++++++++++++++++" +
"++++++++++++++++++++++++++++++");
//Get a value for the exponent n from the user,
//and perform input validation to ensure that it is
//a non-negative number.
do
{
System.out.println("Enter an integer for n:");
n = keyboard.nextInt();
if (n < 0) System.out.println("ERROR: Please enter a non-negative " +
Computer Science Notes
Chapter 4
Page 2 of 21
"integer for n.");
}while (n < 0);
//Get values for the coefficients of x and y.
System.out.println("Enter any number for a:");
a = keyboard.nextDouble();
System.out.println("Enter any number for b:");
b = keyboard.nextDouble();
//Print out Pascal's triangle to show the user how the
//coefficients in the expansion can be computed easily
//by a human.
//
1
//
1
1
//
1
2
1
//
1
3
3
1
// 1
4
6
4
1
//Humans compute the triangle by adding together adjacent
//numbers from the row above, but this program will compute
//entries in the triangle using the binomial coefficient.
System.out.println("\nHere is Pascal's Triangle up to n = " + n + ".");
for (int row = 0; row <= n; row++)
{
//Print leading blank spaces to get the numbers to line up.
for (int k = 0; k<=(n-row-1); k++)
System.out.print("
");
for (int k = 0; k<=row; k++)
{
//Compute the binomial coefficient
//row choose k = row! / (k!*(row - k)!).
long binomialCoefficient = 1;
for (int i = 1; i <= row; i++)
binomialCoefficient *= i;
for (int i = 1; i <= k; i++)
binomialCoefficient /= i;
for (int i = 1; i <= (row-k); i++)
binomialCoefficient /= i;
//Print the entry in the triangle with blank space
//to maintain alignment.
System.out.printf("%5d
", binomialCoefficient);
}
System.out.println();
}
//Print out the general binomial expansion to show the user
//How the coefficients are used.
System.out.println("\nHere is a simple binomial expansion for " +
"n = " + n + ".");
System.out.println("(c + d)^" + n + " = ");
for (int k = 0; k<=n; k++)
{
//Print leading blank space so each term aligns with its
//corresponding entry in the triangle above.
System.out.print(" ");
for (int numBlanks = 0; numBlanks < k; numBlanks++)
System.out.print("
");
//Print a '+' sign, if necessary.
if (k <= n && k > 0)
System.out.print(" + ");
//Compute the binomial coefficient
Computer Science Notes
Chapter 4
Page 3 of 21
//n choose k = n! / (k!*(n - k)!).
long binomialCoefficient = 1;
for (int i = 1; i <= n; i++)
binomialCoefficient *= i;
for (int i = 1; i <= k; i++)
binomialCoefficient /= i;
for (int i = 1; i <= (n-k); i++)
binomialCoefficient /= i;
System.out.println("(" + binomialCoefficient + ")(c^" +
(n-k) + ")(d^" + k + ")");
}
//Finally, print out the full binomial expansion
//for the user.
System.out.println("\nHere is your binomial expansion.");
System.out.println("((" + a + ")x + (" + b + ")y)^" + n + " = ");
for (int k = 0; k<=n; k++)
{
//Print leading blank space so each term aligns with its
//corresponding entry in the triangle above.
System.out.print(" ");
for (int numBlanks = 0; numBlanks < k; numBlanks++)
System.out.print("
");
//Print a '+' sign, if necessary.
if (k <= n && k > 0)
System.out.print(" + ");
//Compute the binomial coefficient
//n choose k = n! / (k!*(n - k)!).
long binomialCoefficient = 1;
for (int i = 1; i <= n; i++)
binomialCoefficient *= i;
for (int i = 1; i <= k; i++)
binomialCoefficient /= i;
for (int i = 1; i <= (n-k); i++)
binomialCoefficient /= i;
System.out.println("("
+ binomialCoefficient * Math.pow(a,n-k) * Math.pow(b,k)
+ ")x^" + (n-k) + "y^" + k);
}
System.out.println("\nEnter");
System.out.println("1 if you want to continue");
System.out.println("0 if you wish to stop:");
repeatSentinel = keyboard.nextInt();
}while (repeatSentinel == 1);
System.out.println("Program Chap04Basics has terminated.");
}//end method main(String[])
}//end of class Chap04Basics
Computer Science Notes
Chapter 4
Page 4 of 21
This program will print the expansion of a binomial of the form (ax + by)^n.
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Enter an integer for n:
4
Enter any number for a:
2
Enter any number for b:
-3
Here is Pascal's Triangle up to n = 4.
1
1
1
1
2
1
1
3
3
1
1
4
6
4
1
Here is a simple binomial expansion for n = 4.
(c + d)^4 =
(1)(c^4)(d^0)
+ (4)(c^3)(d^1)
+ (6)(c^2)(d^2)
+ (4)(c^1)(d^3)
+ (1)(c^0)(d^4)
Here is your binomial expansion.
((2.0)x + (-3.0)y)^4 =
(16.0)x^4y^0
+ (-96.0)x^3y^1
+ (216.0)x^2y^2
+ (-216.0)x^1y^3
+ (81.0)x^0y^4
Enter
1 if you want to continue
0 if you wish to stop:
Book’s Statement of Skills:
1. To use while, do-while, and for loop statements to control the repetition of statements. (4.2 – 4.4)
2. To understand the flow of control in loop statements. (4.2 – 4.4)
3. To use Boolean expressions to control loop statements. (4.2 – 4.4)
4. To know the similarities and differences between the three types of loops. (4.5)
5. To write nested loops. (4.6)
6. To learn techniques for minimizing numerical error (4.7)
7. To learn loops from a variety of examples (4.8)
8. To implement program control with break and continue. (4.9)
9. (GUI) To control a loop with a confirmation dialog. (4.10)
Computer Science Notes
Chapter 4
Page 5 of 21
Section 4.1: Introduction
A loop is a structure that allows you to repeat a block of statements as many times as is desired or needed (or
more, if your program has an infinite loop).
Example: Print Welcome to Java! 100 times
Without loops
Using loops
// Print “Welcome to Java!” 100 times
System.out.println("Welcome to Java!”);
System.out.println("Welcome to Java!”);
System.out.println("Welcome to Java!”);
System.out.println("Welcome to Java!”);
System.out.println("Welcome to Java!”);
// Print “Welcome to Java!” 100 times
for (int count = 1; count <= 100; count++)
System.out.println("Welcome to Java!”);
//… 94 more println statements…
System.out.println("Welcome to Java!”);
Section 4.2: The while Loop
A while loop checks to see if a condition is true, executes a block of code if the condition is true, and then keeps
checking the condition and executing the block of code as long as the condition is true.
Syntax of a while statement:
while (condition)
{
conditionTrueStatement(s);
}
nextStatement;



When the condition is true, the program executes conditionTrueStatement(s).
When conditionTrueStatement(s) are done executing, the program goes back to the condition, and if
the condition is still true, the program executes conditionTrueStatement(s) again.
This process of looping back to the condition keeps repeating until the condition is false, at which point
the program jumps down and executes nextStatement.
Example:
public class PrintLoop
{
public static void main(String[] args)
{
// Print "Welcome to Java!" 100 times
int counter = 1;
int maxPrintLines = 100;
while (counter <= maxPrintLines)
{
System.out.println("Welcome to Java!");
counter++;
}
}
}
Computer Science Notes
Chapter 4
Page 6 of 21
Example:
import java.util.Scanner;
public class Guessing7Game
{
public static void main(String[] args)
{
// a loop that plays a guessing game
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a guess:");
int guess = keyboard.nextInt();
while (guess != 7)
{
System.out.println("Bad guess.");
System.out.println("Enter a guess:");
guess = keyboard.nextInt();
}
System.out.println("You guessed correctly!");
}
}
Example: INPUT VALIDATION: Notice that this loop keeps on repeating until a valid piece of data is
entered.
import java.util.Scanner;
public class CircleCircumference
{
public static void main(String[] args)
{
System.out.println("This program will compute the circumference of " +
"a circle given its radius.");
Scanner keyboard = new Scanner(System.in);
// Get the user’s input for a circle radius
System.out.println("Enter the radius of a circle:");
double radius = keyboard.nextDouble();
// a loop that validates an input for a radius
while (radius < 0.0)
{
System.out.println("Bad entry; you entered r = " + radius +
", and the radius of a circle should NOT be negative.");
System.out.println("Enter a positive radius for the circle:");
radius = keyboard.nextDouble();
}
System.out.println("For a circle of radius " + radius +
", the circumference is: " + (2*Math.PI*radius) + ".");
}
}
Computer Science Notes
Chapter 4
Page 7 of 21
Example: PROGRAM REPETITION: This is useful if you want to repeat the entire body of a program.
import java.util.Scanner;
public class CompareNumbers
{
/** Prompts the user for two numbers to compare.
* @param args is not used
*/
public static void main (String[ ] args)
{
System.out.println("This program compare two numbers as many times as you
like.");
//Declare variables for the data to be read in: two numbers for comparison.
double num1, num2;
//Create a Scanner object for reading in the user's input
Scanner keyboard = new Scanner(System.in);
int compareAgain = 1;
while (compareAgain == 1)
{
//get the user's data
System.out.println("\nPlease enter a number:");
num1 = keyboard.nextDouble();
System.out.println("Please enter a second number:");
num2 = keyboard.nextDouble();
//Compare the numbers
System.out.println("Here is the
if (num1 < num2)
System.out.println(num1 +
else if (num1 > num2)
System.out.println(num1 +
else
System.out.println(num1 +
comparison:");
" < " + num2);
" > " + num2);
" = " + num2);
System.out.println("Enter 1 to continue or 0 to quit:");
compareAgain = keyboard.nextInt();
}
System.out.println("\nProgram Terminated.");
}
}
Computer Science Notes
Chapter 4
Page 8 of 21
Example: Notice that a variable can be defined in a loop, but that it only exists in memory while the loop
is executing.
public class InvestmentMaturityDate
{
public static void main(String[] args)
{
// a loop that computes how many years
// until a $10,000 investment reaches a target balance of $20,000
// at an interest rate of 8%
double initialBalance = 10000.00;
double targetBalance = 20000.00;
double rate = 0.08;
double currentBalance = initialBalance;
int years = 0;
while (currentBalance < targetBalance)
{
years++;
double interest = currentBalance * rate;
currentBalance = currentBalance + interest;
}
//NOTE: the interest variable no longer exists outside the loop
//SO, it can not be used for output or further calculations.
System.out.println("An investment of $" + initialBalance +
" earning " + (rate*100) + "% interest per year" +
" grows to at least $" + targetBalance +
" after " + years + " years.");
System.out.printf("In fact, the investment is worth $%,9.2f " +
" at the end of the %2d years\n", currentBalance, years);
}
}
Computer Science Notes
Chapter 4
Page 9 of 21
Example: A loop that executes a pre-determined number of times.
public class FutureValueOfAnInvestment
{
public static void main(String[] args)
{
// a loop that computes the value of a $10,000 investment
// after 5 years when earning at an interest rate of 8%
double initialBalance = 10000.00;
double rate = 0.08;
int maxYears = 5;
double currentBalance = initialBalance;
int years = 0;
while (years < maxYears)
{
years++;
double interest = currentBalance * rate;
currentBalance = currentBalance + interest;
}
System.out.println("An investment of $" +
String.format("%,10.2f",initialBalance) +
" invested at " + (rate*100) + "% interest per year " +
"grows to $" + String.format("%,10.2f",currentBalance) +
" after " + maxYears + " years.");
}
}
Computer Science Notes
Chapter 4
Page 10 of 21
It is VERY common that loops are controlled by an integer variable that gets incremented every time the loop
executes. Such controlling integer variables are called control variables or counters.
Common errors with counters:

Infinite loops: due to incrementing the counter incorrectly or not at all, or having a bad condition.
The following loop is “infinite” because the counter years never gets incremented, so it will always be less
than maxYears.
while (years < maxYears)
{
double interest = currentBalance * rate;
currentBalance = currentBalance + interest;
}

Off-by-one errors: due to using a bad starting value for the counter or an incorrect condition.
The following loop will compute one year too many of interest payments because when starting a counter at
zero, you need to terminate the loop at one less than the number of iterations you want.
int years = 0;
while (years <= maxYears)
{
years++;
double interest = currentBalance * rate;
currentBalance = currentBalance + interest;
}
Section 4.2.1: Problem: Guessing Numbers

See www.cs.armstrong.edu/liang/intro7e/book/GuessNumberOneTime.java

See www.cs.armstrong.edu/liang/intro7e/book/GuessNumber.java
Section 4.2.2: Problem: An Advanced Math Learning Tool

See www.cs.armstrong.edu/liang/intro7e/book/SubtractionQuizLoop.java
Computer Science Notes
Chapter 4
Page 11 of 21
Section 4.2.3: Controlling a Loop with a Sentinel Value
If you want the user of a program to decide when to end a loop, then another trick you can use is to give the user
a special input value to enter that does not make sense in terms of the other data being entered. When this
special input value is encountered, then the loop ends. This special input value is called a sentinel value.
Example: Computing the average of a list of user-entered numbers.
import java.util.Scanner;
public class Average
{
public static void main (String[ ] args)
{
System.out.println("This program computes the average of non-negative " +
"numbers.");
//Declare variables for the data entries, number of entries, and average.
double dataEntry = 0.0, average = 0.0;
int numEntries = 0;
//Create a Scanner object for reading in the user's input
Scanner keyboard = new Scanner(System.in);
while (dataEntry >= 0.0)
{
//get the user's data
System.out.println("Please enter a number (or a negative value " +
"to quit):");
dataEntry = keyboard.nextDouble();
if (dataEntry >= 0.0)
{
average += dataEntry;
numEntries++;
}
}
if (numEntries > 0)
{
average = average / numEntries;
System.out.println("\nThe average of your " + numEntries +
" values is: " + average);
}
else
System.out.println("\nNo data enetered.");
System.out.println("\nProgram Terminated.");
}//end main()
}
This program
Please enter
Please enter
Please enter
Please enter
computes
a number
a number
a number
a number
the
(or
(or
(or
(or
average of
a negative
a negative
a negative
a negative
The average of your 3 values is: 3.0
Program Terminated.
non-negative numbers.
value to quit):2
value to quit):3
value to quit):4
value to quit):-1
Computer Science Notes
Chapter 4
Page 12 of 21
Section 4.3: The do-while Loop
A do-while loop executes the body of the loop before checking the condition. This can result in slightly more
efficient code when you know you want the loop to execute at least once.
Notice the semicolon after the while clause.
Syntax of a do-while statement:
do
{
Statement(s);
} while (condition);
nextStatement;


When the condition is true, the program goes back to the do and executes the Statement(s).
When the condition is false, the program executes nextStatement.
Example: Notice that the program does not have to have the prompt and input lines of code repeated like
in the while loop, but that you do need an if statement to handle the error message to the user when an
incorrect guess is entered.
import java.util.Scanner;
public class Guessing7Game
{
public static void main(String[] args)
{
// a loop that plays a guessing game
Scanner keyboard = new Scanner(System.in);
int guess;
do
{
System.out.println("Enter a guess:");
guess = keyboard.nextInt();
if (guess != 7) System.out.println("Bad guess.");
}
while (guess != 7);
System.out.println("You guessed correctly!");
}
}
Computer Science Notes
Chapter 4
Page 13 of 21
Section 4.4: for Loops
Loops that depend on the value of an incremented counter for the condition are so common that a new looping
structure called the for loop was created that makes this type loop more efficient:
Syntax of a simple for statement:
for (initial_action; loop_continuation_condition; action_after_each_iteration)
Statement;
nextStatement;
Syntax of a block for statement:
for (initial_action; loop_continuation_condition; action_after_each_iteration)
{
Statement(s);
}
nextStatement;





The initial_action is atatement that is usually used to declare and initialize a control variable for the
loop
As long as the loop_continuation_condition is true, the program executes the Statement(s).
When the loop_continuation_condition is false, the program executes nextStatement.
The action_after_each_iteration is a statement that executes after the last statement in the body of the
loop; it is usually used to adjust the control variable (usually by incrementing it or decrementing it).
Control variables declared inside the header of a loop can not be accessed by statements outside the
loop.
Example: A loop that executes a pre-determined number of times. It is possible to both define and
initialize a variable in the header, but that variable only exists in memory while the loop is executing…
public class FutureValueOfAnInvestment
{
public static void main(String[] args)
{
// a loop that computes the value of a $10,000 investment
// after 5 years when earning at an interest rate of 8%
double initialBalance = 10000.00;
double rate = 0.08;
int maxYears = 5;
double currentBalance = initialBalance;
int years = 0;
for (years = 1; years <= maxYears; years ++)
{
double interest = currentBalance * rate;
currentBalance = currentBalance + interest;
}
System.out.println("An investment of $" +
String.format("%,10.2f",initialBalance) +
" invested at " + (rate*100) + "% interest per year " +
"grows to $" + String.format("%,10.2f",currentBalance) +
" after " + maxYears + " years.");
}
}
Computer Science Notes
Chapter 4
Page 14 of 21
Also notice that the loop could be made more efficient as follows:
for (years = 1; years <= maxYears; years ++)
currentBalance = currentBalance + currentBalance * rate;
Or as follows:
for (years = 1; years <= maxYears; years ++)
currentBalance += currentBalance * rate;
Example:
public class IntegerSum
{
public static void main(String[] args)
{
// a loop that sums the numbers from 1 to 10
int sum = 0;
int lastInteger = 1000;
for (int i= 1; i <= lastInteger; i++)
sum += i;
System.out.println("The sum of integers from 1 to " + lastInteger +
" = " + sum);
}
}
For loop hints:
1. use for loops for their intended purpose; do not change the counter, change the starting value, change the
ending value, or increment the counter in the body of the loop; only do this in the for loop header.
2. don’t forget a semicolon after a for loop in which all the work of the loop is done in the header.
(Bad) Example: This works, but violates hint #1; … notice the semicolon immediately after the
header.
public class InvestmentMaturityDate
{
public static void main(String[] args)
{
// a loop that computes how many years
// until a $10,000 investment reaches a target balance of $20,000
// at an interest rate of 8%
double initialBalance = 10000.00;
double targetBalance = 20000.00;
double rate = 0.08;
double currentBalance = initialBalance;
int years = 0;
for (years = 1;
( currentBalance = currentBalance * (1 + rate) ) < targetBalance;
Computer Science Notes
Chapter 4
Page 15 of 21
years ++) ;
System.out.println("An investment of $" + initialBalance +
" earning " + (rate*100) + "% interest per year" +
" grows to at least $" + targetBalance +
" after " + years + " years.");
System.out.printf("In fact, the investment is worth $%,9.2f " +
" at the end of the %2d years\n", currentBalance, years);
}
}
3. don’t use a semicolon after the header when you want the loop to iterate the statement after the header.
4. don’t use != to test the end of a range; use <= instead.
5. when the counter is defined in the header of a for loop, it only has scope while the loop is iterating; it is
no longer defined after the loop
6. you can declare multiple variables and have multiple updates (all separated by semicolons) in the header
of a for loop, but this is sometimes considered bad form
Computer Science Notes
Chapter 4
Page 16 of 21
Section 4.5: Which Loop to Use?
 While and for loops are pre-test loops.
 Do loops are post-test loops.
 Use a while loop when you want to test the condition first.
 Use a do-while loop when you want the body to execute at least once.
 Use a for loop when you want to test the condition first, and the loop will execute a pre-determined
number of times.
public class IntegerSum
{
public static void main(String[] args)
{
//Sum the numbers from 1 to 1000.
int lastInteger = 1000;
int sum = 0;
//Perform the calculation with a for loop.
for (int i= 1; i <= lastInteger; i++)
sum += i;
System.out.println("The sum of integers from 1 to " + lastInteger +
" = " + sum);
//Perform the calculation with
sum = 0;
int i = 0;
while (i <= lastInteger)
{
sum += i;
i++;
}
System.out.println("The sum of
" = " + sum);
//Perform the calculation with
sum = 0;
i = 0;
do
{
sum += i;
i++;
}while (i < lastInteger+1);
System.out.println("The sum of
" = " + sum);
}
}
The sum of integers from 1 to 1000 = 500500
The sum of integers from 1 to 1000 = 500500
The sum of integers from 1 to 1000 = 500500
a while loop.
integers from 1 to " + lastInteger +
a do loop.
integers from 1 to " + lastInteger +
Computer Science Notes
Chapter 4
Page 17 of 21
Section 4.6: Nested Loops
A nested loop is a loop within another loop. Each time the outer loop iterates, the entire inner loop gets
executed. Nested loops are used when you have to process data that depends on two “dimensions”. One
common application is processing graphics, and another is processing any “two-dimensional” type of
information.
Example: Print a triangular shape as follows:
X
XX
XXX
XXXX
XXXXX
public class PrintRightTriangle
{
public static void main(String[] args)
{
// Print a right triangle of x's.
int maxRows = 5;
for (int row = 1; row <= maxRows; row++)
{
for (int col = 1; col <= row; col++)
{
System.out.print("X");
}
System.out.println();
}
}
}

See www.cs.armstrong.edu/liang/intro7e/book/MultiplicationTable.java
Section 4.7: Minimizing Numerical Errors
Tips:

Use double instead of float.

Use integers to count instead of floating-point numbers.

Process small numbers first.

Add or subtract numbers of similar magnitude.
Computer Science Notes
Chapter 4
Page 18 of 21
Section 4.8: Case Studies
Section 4.8.1: Problem: Finding the Greatest Common Divisor

See www.cs.armstrong.edu/liang/intro7e/book/GreatestCommonDivisor.java
Section 4.8.2: Problem: Finding the Sales Amount

See www.cs.armstrong.edu/liang/intro7e/book/FindSalesAmount.java
Section 4.8.3: Problem: Displaying a Pyramid of Numbers

See www.cs.armstrong.edu/liang/intro7e/book/PrintPyramid.java
Section 4.9: Keywords break and continue

break immediately ends the innermost loop that contains it. break breaks out of a loop. It is generally
used with an if statement.

continue only ends the current iteration of the loop that contains it. Program control goes to the end of
the loop body. continue breaks out of an iteration. It is generally used with an if statement.

See www.cs.armstrong.edu/liang/intro7e/book/TestBreak.java

See www.cs.armstrong.edu/liang/intro7e/book/TestContinue.java

See www.cs.armstrong.edu/liang/intro7e/book/GuessNumberUsingBreak.java
Section 4.9.1: Problem: Displaying Prime Numbers

See www.cs.armstrong.edu/liang/intro7e/book/PrimeNumber.java
Computer Science Notes
Chapter 4
Page 19 of 21
Random Numbers using the Random Class and their use in Simulations
A lot of times, you need a random number, like to simulate the roll of some dice, a card picked at random from
a deck, or other things. The Random class generates random numbers for you.

You need to import class java.util.Random;

The nextInt(n) method returns a random integer between 0 (inclusive) and n (exclusive).

The nextDouble() method returns a random floating-point number between 0 (inclusive) and 1
(exclusive).
Example: simulate a pair of dice.
import java.util.Random;
import java.util.Scanner;
/** Simulates rolling dice.
*/
public class Dice
{
/** Rolls the dice.
* @param args is not used
*/
public static void main (String[] args)
{
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
int repeatSentinel;
System.out.println("This program will simulate the roll " +
"of a pair of dice.");
do
{
int die1 = generator.nextInt(6) + 1;
int die2 = generator.nextInt(6) + 1;
System.out.println("The roll is: " + die1 + " and " + die2);
System.out.println("Enter 1 to continue or 0 to quit.");
repeatSentinel = keyboard.nextInt();
}while (repeatSentinel > 0);
}
}
Computer Science Notes
Chapter 4
Page 20 of 21
Example: Compute the area of a circle by “throwing darts” at a quarter circle of radius 1 in the square of
0 < x < 1 and 0 < y < 1. Techniques like this are called Monte Carlo simulations.
import java.util.Random;
/** Computes area of a circle using random numbers.
*/
public class MonteCarloCircle
{
/** Computes area of a circle using random numbers.
* @param args is not used
*/
public static void main (String[ ] args)
{
Random generator = new Random();
int totalPoints = 10000;
int interiorHits = 0;
System.out.println("This program will compute the approximate " +
"area of a circle of radius 1 using " + totalPoints +
" random numbers.\n");
for (int i = 1; i <= totalPoints; i++)
{
double x = generator.nextDouble();
double y = generator.nextDouble();
if ( (x*x + y*y) < 1 ) interiorHits++;
}
System.out.println("The approximate area of a radius=1 circle is "
+ 4. * interiorHits / totalPoints);
}
}
Section 4.10: Controlling a Loop with a Confirmation Dialog
If you want the user of a program to decide when to end a loop, you can prompt them if they want to continue
using a confirmation dialog box (as opposed to prompting for input from the console in some of the examples
above).
Computer Science Notes
Chapter 4
Page 21 of 21
Example: PROGRAM REPETITION using a confirmation dialog.
import javax.swing.JOptionPane;
public class Chap04BasicsGUI
{
/** Prompts the user for two numbers to compare.
* @param args is not used
*/
public static void main (String[ ] args)
{
//Tell the user what the program does
JOptionPane.showMessageDialog(null, "This program compare two " +
"numbers as many times as you like."
, "Chap04BasicsGUI Intro",
JOptionPane.INFORMATION_MESSAGE);
//Declare variables for the data to be read in: two numbers for comparison.
double num1, num2;
String numberString;
int compareAgain = JOptionPane.YES_OPTION;
while (compareAgain == JOptionPane.YES_OPTION)
{
//get the user's data
numberString = JOptionPane.showInputDialog(null, "Please enter the " +
"first number:", "First Number",
JOptionPane.QUESTION_MESSAGE);
num1 = Double.parseDouble(numberString);
numberString = JOptionPane.showInputDialog(null, "Please enter the " +
"second number:", "Second Number",
JOptionPane.QUESTION_MESSAGE);
num2 = Double.parseDouble(numberString);
//Compare the numbers
String resultString =
if (num1 < num2)
resultString +=
else if (num1 > num2)
resultString +=
else
resultString +=
"Here is the comparison:\n";
(num1 + " < " + num2);
(num1 + " > " + num2);
(num1 + " = " + num2);
JOptionPane.showMessageDialog(null, resultString, "Results",
JOptionPane.INFORMATION_MESSAGE);
compareAgain = JOptionPane.showConfirmDialog(null,
"Do you want to continue?");
}
JOptionPane.showMessageDialog(null, "Program Terminated.", "All Done",
JOptionPane.INFORMATION_MESSAGE);
}
}