65
MELJUN CORTES,MBA,MPA,BSCS,ACS MELJUN CORTES,MBA,MPA,BSCS,ACS. Chapter 6 JAVA JAVA Repetition Repetition Statements Statements MELJUN CORTES MELJUN CORTES

MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

Embed Size (px)

DESCRIPTION

MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

Citation preview

Page 1: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS.

Chapter 6JAVAJAVA

Repetition Repetition StatementsStatements

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Chapter 6 ObjectivesAfter you have read and studied this chapter, you should be able to• Implement repetition control in a

program by using while statements.• Implement repetition control in a

program by using do-while statements.

• Implement a generic loop-and-a-half repetition control statement.

• Implement repetition control in a program by using for statements.

Page 3: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Chapter 6 Objectives, cont.After you have read and studied this chapter, you should be able to• Nest a loop repetition statement

inside another repetition statement.• Choose the appropriate repetition

control statement for a given task.• Prompt the user for a yes/no reply by

using the showConfirmDialog method from the JOptionPane class.

• (Optional) Write simple recursive methods.

Page 4: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.1 The while StatementRepetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met.

Java has three repetition statements:• while• do-while• for

Page 5: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.1 The while StatementIn Java, while statements follow a general format:

while ( <boolean expression> )<statement>

For example:int sum = 0, number = 1;while (number <= 100){sum = sum + number;number = number + 1;

}

Page 6: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.1 The while StatementRepetition statements are also called loop statements, and the <statement> is known as the loop body.

As long as the <boolean expression> is true, the loop body is executed.

Page 7: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.1Correspondence of the example while statement to the general format.

Page 8: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.2A diagram showing the control flow of a while statement.

Page 9: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.1 The while StatementIn a count-controlled loop, the loop body is executed a fixed number of times.

In a sentinel-controlled loop, the loop body is executed repeatedly until a designated value, called a sentinel, is encountered.

Page 10: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.2 Pitfalls in Writing Repetition Statements

When writing repetition statements, it is important to ensure that the loop will eventually terminate.

There are several different types of potential programming problems we should keep in mind as we develop our programs.

Page 11: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.2 Pitfalls in Writing Repetition Statements

Infinite loop

int product = 0;while (product < 5000) {product = product * 5;

}Because product is initialized to 0, product will never be larger than 5000 (0 = 0 * 5), so the loop will never terminate.

Page 12: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.2 Pitfalls in Writing Repetition Statements

Overflow error

int count = 1;while (count != 10) {count = count + 2;

}

In this example, (the while statement of which is also an infinite loop), count will equal 9 and 11, but not 10.

Page 13: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.2 Pitfalls in Writing Repetition Statements

An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold.

In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value.

Page 14: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.2 Pitfalls in Writing Repetition Statements

Real numbers should not be used in testing or increment, because only an approximation of real numbers can be stored in a computer.

The off-by-one error is another frequently-encountered pitfall.

Page 15: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.3 The do-while StatementThe while statement is a pretest loop, because the test is done before the execution of the loop body. Therefore, the loop body may not be executed.

The do-while statement is a posttest loop. With a posttest loop statement, the loop body is executed at least once.

Page 16: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.3 The do-while StatementThe format of the do-while statement is:do

<statement>while (<boolean expression>);

The <statement> is executed until the <boolean expression> becomes false.

Page 17: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.3 The do-while Statementint sum = 0, number = 1;do{

sum += number;number++;

} while (sum <=1000000);

Page 18: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.3Correspondence of the example do-while statement to the general format.

Page 19: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.4A diagram showing the control flow of the do-while statement.

Page 20: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.4 Loop-and-a-Half Repetition ControlLoop-and-a-half repetition control can be used to test a loop’s terminating condition in the middle of the loop body.

It is implemented by using reserved words while, if, and break.

Page 21: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.4 Loop-and-a-Half Repetition ControlString name;while (true){

name = JOptionPane.showInputDialog(null, “Your name”);

if (name.length() > 0) break;

JOptionPane.showMessageDialog(null, “Invalid Entry.” + “You must enter at least one character.”);

}

Page 22: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.5A diagram showing the control flow of a loop-and-a-half statement.

Page 23: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.4 Loop-and-a-Half Repetition ControlBe aware of two concerns when using the loop-and-a-half control:

• The danger of an infinite loop. The boolean expression of the while statement is true, which will always evaluate to true. If we forget to include an if statement to break out of the loop, it will result in an infinite loop.

Page 24: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.4 Loop-and-a-Half Repetition Control• Multiple exit points. It is possible,

although complex, to write a correct control loop with multiple exit points (breaks). It is good practice to enforce the one-entry one-exit control flow.

Page 25: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.5 Confirmation DialogA confirmation dialog can be used to

prompt the user to determine whether to continue a repetition or not.

JOptionPane.showConfirmDialog(null,/*prompt*/ “Play Another Game?”,/*dialog title*/ “Confirmation”,/*button options*/ JOptionPane.YES_NO_OPTION);

Executing the code above will result in Fig. 6.6.

Page 26: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.6A confirmation dialog created by using the showConfirmDialog method of the JOptionPane class.

Page 27: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.5 Confirmation DialogUsed in a loop statement:

boolean keepPlaying = true;int selection;while (keepPlaying){

//code to play one game comes hereselection = JOptionPane.showConfirmDialog(null,

“Play Another Game”,“Confirmation”,JOptionPane.YES_NO_OPTION);

keepPlaying = (selection == JOptionPane.YES_OPTION);

}

Page 28: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.6 The for StatementThe format of the for statement is as follows:

for (<initialization>; <boolean expression>; <increment>)

<statement>

int i, sum = 0;for (i = 1,i <=100, i++){sum += i; //equivalent to sum = sum + 1;

}

Page 29: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.7Correspondence of the example for statement to the general format

Page 30: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.8A diagram showing the control flow of the example for statement.

Page 31: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.6 The for StatementThe variable i in the example statement is called a control variable. It keeps track of the number of repetitions.

The <increment> can be by any amount, positive or negative.

Page 32: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.6 The for Statement/*Chapter 6 Sample Program: Dropping a Watermelon

File: Ch6DroppingWaterMelon.java*/

import javabook.*;import java.io.*;

class Ch6DroppingWaterMelon {

public static void main(String[] args){

double initialHeight, position, touchTime;

Page 33: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.6 The for Statement Scanner scanner = new Scanner(System.in); scanner.useDelimiter( System.getProperty("line.separator"));

System.out.print("Initial Height:"); initialHeight = scanner.nextDouble();

touchTime = Math.sqrt(initialHeight / 16.0); touchTime = Math.round(touchTime * 10000.0) /

10000.0; //convert to four decimal places

System.out.println( "\n\n Time t Position at Time t \n");

Page 34: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.6 The for Statement for (int time = 0; time < touchTime; time++) { position = -16.0 * time*time + initialHeight; System.out.print(" " + time); System.out.println(" " + position); }

//print the last second System.out.println(" " + touchTime + " 0.00");

System.out.println("\n\n\n"); }}

Page 35: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.6 The for StatementAn illustration of the Ch6DroppingWaterMelon.java program.

Page 36: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.9The positions of a watermelon dropped from a height of 500 ft.

Page 37: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.7 Nested-for StatementsNested-for statements are for statements embedded within other for statements.

int price;for (int width = 11; width <=20, width++){

for (int length = 5, length <=25, length+=5){

price = width * length * 19; //$19 per sq. ft. System.out.print (“ “+ price);}//finished one row; move on to next rowSystem.out.println(“”);

}

Page 38: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.10The price table for carpets ranging in size from 11 × 5 to 20 × 25 ft. whose unit price is $19 per sq. ft.

Page 39: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.7 Nested-for StatementsThe outer for statement ranges from the first row (width = 11) to the last row (width = 20).

For each repetition of the outer for, the inner for statement is executed, which ranges from the first column (length = 5) to the fifth (length = 25).

Page 40: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.8 Formatting OutputTo align values with varying numbers of digits, we must vary the number of spaces in front of the values.

The idea behind formatted output is to allocate the same amount of space for the output values and align the values within the allocated space.

Page 41: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.11The price table for carpets with $15 per sq. ft. and width ranging from 5-14 ft.

Page 42: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.8 Formatting OutputWe call the space occupied by an output value the field. The number of characters allocated to a field is the field width.

Page 43: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.12How to place a varying number of spaces to align the output values. Hyphen is used here to indicate the blank space.

Page 44: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.8 Formatting OutputWe use the Formatter class to format

the output.First we create an instance of the classFormatter formatter =

new Formatter(System.out);

Then we call its format methodint num = 467;formatter.format("%6d", num);

This will output the value with the field width of 6.

Page 45: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.8 Formatting OutputThe general syntax is

format(<control string>, <expr1>, <expr2>, . . . )

int num1 = 34, num2 = 9; int num3 = num1 + num2; formatter.format("%3d + %3d = %5d",

num1, num2, num3);

Page 46: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.8 Formatting Output/*Chapter 6 Sample Program: Sample formatting statements

File: Ch6CarpetPriceTableWithFormat.java*/

//import javabook.*;import java.io.*;

class Ch6CarpetPriceTableWithFormat { public static void main (String[] args){

int price;

//print out the colum labels System.out.print(" ");

Page 47: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.8 Formatting Output for (int colLabel = 5; colLabel <=25; colLabel += 5) { System.out.format("%8d", colLabel); }

System.out.println(""); System.out.println("");

//print out rows of prices for (int width = 5; width <= 14; width++) {

System.out.format("%3d", width);

for (int length = 5; length <= 25; length += 5) { price = width * length * 15;

System.out.format("%8d", price); }

//finished one row; now move on to the next row System.out.println(""); }

System.out.println(""); System.out.println(""); }}

Page 48: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

Fig. 6.13Carpet price table of Fig. 6.11 with proper alignment.

Page 49: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan TablesThe goal of this exercise is to design a program that generates a loan table. The table will compare different monthly payments for a set loan amount, with varying loan periods in each column and different interest rates in each row.

Page 50: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan TablesThe start method can be expressed as

tell the user what the program does;prompt the user “Do you want to generate a loan table?”;

while (the user says YES){input the loan amount;generate the loan table;prompt the user “Do you want another loan table?”;

}

Page 51: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan TablesThe start method was expressed in pseudocode.

Pseudocode is an informal language used to express an algorithm.

It is useful in clarifying the purpose or function of the program without being tied down to the syntactic rules of a programming language.

Page 52: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan Tablespublic void start () { int response; describeProgram();

response = prompt(“Generate a loan table?”); while (response == JOptionPane.YES_OPTION){

loanAmount = getLoanAmount(); //get inputgenerateLoanTable(loanAmount);//generate

table

response = prompt(“Generate another loan table?”);

}}

Page 53: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan Tables

private int prompt(String question){

int reply;

reply = JOptionPane.showConfirmDialog(null, question,“Confirmation”,JOptionPane.YES_NO_OPTION);

return reply;}

Page 54: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan TablesOther methods in the program:

describeProgram: tells the user what the program does if the user requests it.

getLoanAmount: gets the loan amount from the user.

generateLoanTable: generates the loan table.

Page 55: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.9 Loan TablesTo compute the monthly loan payment, reuse the Loan class defined in Chapter 4.

Page 56: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generation The method random is called a pseudorandom number generator and returns a number of type double that is greater than or equal to 0.0 but less than 1.0.

The generated number is called a pseudorandom number because it is not truly random.

Page 57: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number GenerationIf we want to generate an integer, and the number returned from the random method ranges from 0.0 up to (but not including) 1.0, we must perform a conversion so the number will fall within the desired range.

Use the formula:Y = {X × (max – min + 1)} + min

where X is the number returned by random.

Page 58: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number GenerationThe formula is thus expressed in Java:

//assume correct values are assigned to//‘max’ and ‘min’

int randomNumber = (int) (Math.floor(Math.random *

max-min+1)) + min);

Page 59: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number GenerationThe following program generates N random numbers between 1 and 4 to simulate the suit of a drawn card.

It keeps one counter for each suit, and increments the matching counter after a random number is generated.

At the end of the generation, it prints the ratio count/N.

Page 60: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generation/*Chapter 6 Sample Program: Test the random number generator

File: Ch6TestRandomGenerator.java*/

import javax.swing.*;import java.util.*;

class Ch6TestRandomGenerator {

private static final int CLUB = 1; private static final int SPADE = 2; private static final int HEART = 3; private static final int DIAMOND = 4;

public static void main( String[] args ) { Ch6TestRandomGenerator tester = new

Ch6TestRandomGenerator(); tester.start(); }

Page 61: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generationpublic void start( ) { long N; while (keepTesting()) { N = getSize(); generate(N); }}

private long getSize( ) { String inputStr; long size;

while (true) { inputStr = JOptionPane.showInputDialog(null, "Enter size:");

size = Long.parseLong(inputStr); if (size > 0) break; //input okay so exit

JOptionPane.showMessageDialog(null, "Input must be positive");

} return size;}

Page 62: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generationprivate void generate(long size) {

Date startTime, endTime; int suit; long clubCnt, spadeCnt, heartCnt, diamondCnt;

clubCnt = spadeCnt = heartCnt = diamondCnt = 0;

startTime = new Date(); for (int i = 0; i < size; i++) {

suit = getRandom(CLUB, DIAMOND);

switch (suit) { case CLUB: clubCnt++; break;

case SPADE: spadeCnt++; break;

case HEART: heartCnt++; break;

Page 63: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generation case DIAMOND: diamondCnt++; break;

default: //default case should never happen JOptionPane.showMessageDialog(null,"Internal Error");

System.exit(0); //terminate the program }

}

endTime = new Date();

System.out.println("N is " + size + "\n");System.out.println("Club: " + clubCnt + " " + (double)clubCnt/size);

System.out.println("Spade: " + spadeCnt + " " + (double)spadeCnt/size);

System.out.println("Heart: " + heartCnt + " " + (double)heartCnt/size);

System.out.println("Diamond: " + diamondCnt + " " + (double)diamondCnt/size);

Page 64: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generation double elapsedTimeInSec = (double) (endTime.getTime() - startTime.getTime())/1000.0;

System.out.println("Elapsed time (sec): " + elapsedTimeInSec );

System.out.println("\n");}

private int getRandom(int min, int max) { int randomNumber = (int) (Math.floor(Math.random() * (max-min+1)) + min);

return randomNumber;}

private boolean keepTesting( ) { boolean result; int response = JOptionPane.showConfirmDialog(null, /*prompt*/ "Perform Test?", /*dialog title*/ "Random Number Generator", /*button options*/ JOptionPane.YES_NO_OPTION);

Page 65: MELJUN_CORTES (COMPUTER SCIENCE LECTURE)

MELJUN CORTES,MBA,MPA,BSCS,ACSMELJUN CORTES,MBA,MPA,BSCS,ACS

6.10 Random Number Generationif (response == JOptionPane.YES_OPTION) {

result = true; } else { result = false; }

return result; }}