chapter 11 slides

70

Upload: etoile

Post on 14-Jan-2016

52 views

Category:

Documents


1 download

DESCRIPTION

Exposure Java. Chapter 11 Slides. Control Structures II. PowerPoint Presentation created by: Mr. John L. M. Schram. From Materials Created by Mr. Leon Schram. // Java1101.java // This program demonstrates using multiple variables in a loop. public class Java1101 { - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 11 Slides
Page 2: Chapter 11 Slides

// Java1101.java// This program demonstrates using multiple variables in a <for> loop.

public class Java1101{

public static void main(String args[]){

int p, q;for (p=1, q=5; p <= 5; p++,q--)

System.out.println("p = " + p + " q = " + q);}

} Java1101.java Output

p = 1 q = 5p = 2 q = 4p = 3 q = 3p = 4 q = 2p = 5 q = 1

Page 3: Chapter 11 Slides

// Java1102.java// This program demonstrates a practical example of using multiple// variables in a <for> loop. This program counts the number of// quarters, as well as the value of the quarters.

public class Java1102{

public static void main(String args[]){

int count;double value;for (count = 1, value = 0.25; count <= 20; count++, value+=0.25)

System.out.println(count + " Quarter(s) equals " + value);}

}

Java1102.java Output

1 Quarter(s) equals 0.252 Quarter(s) equals 0.53 Quarter(s) equals 0.754 Quarter(s) equals 1.05 Quarter(s) equals 1.256 Quarter(s) equals 1.57 Quarter(s) equals 1.758 Quarter(s) equals 2.09 Quarter(s) equals 2.2510 Quarter(s) equals 2.511 Quarter(s) equals 2.7512 Quarter(s) equals 3.013 Quarter(s) equals 3.2514 Quarter(s) equals 3.515 Quarter(s) equals 3.7516 Quarter(s) equals 4.017 Quarter(s) equals 4.2518 Quarter(s) equals 4.519 Quarter(s) equals 4.7520 Quarter(s) equals 5.0

Page 4: Chapter 11 Slides

// Java1103.java// This program introduces text window input using the // InputStreamReader class found in the java.io package.import java.io.*; // Line 1public class Java1103{

public static void main (String args[]) throws IOException // Line 2{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); // Line 3

String name;int age;double gpa;

System.out.print("Enter Name ===>> "); // Line 4name = input.readLine(); // Line 5

System.out.print("Enter Age ===>> ");age = Integer.parseInt(input.readLine()); // Line 6

System.out.print("Enter GPA ===>> ");gpa = Double.parseDouble(input.readLine()); // Line 7

System.out.println();System.out.println("Name: " + name);System.out.println("Age: " + age);System.out.println("GPA: " + gpa);

}}

Java1103.java Output

Enter Name ===>> Isolde EchleEnter Age ===>> 29Enter GPA ===>> 3.785

Name: Isolde EchleAge: 29GPA: 3.785

Page 5: Chapter 11 Slides

Keyboard Text Window Input

import java.io.*;// Line 1

public class Java1103{ public static void main (String args[]) throws IOException // Line 2 { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); // Line 3 String name; int age; double gpa; System.out.print("Enter Name ===>> "); // Line 4 name = input.readLine(); // Line 5 System.out.print("Enter Age ===>> "); age = Integer.parseInt(input.readLine()); // Line 6 System.out.print("Enter GPA ===>> "); gpa = Double.parseDouble(input.readLine()); // Line 7

Page 6: Chapter 11 Slides

Keyboard Text Input Line 1

import java.io.*;

This import statement gives access to the input/output classes of the java.io package.

Page 7: Chapter 11 Slides

Keyboard Text Input Line 2

public static void main (String args[ ]) throws IOException

The statement throws IOException alerts Java of possible errors. Specifically errors during input and output, which need to be ignored or thrown away.

Page 8: Chapter 11 Slides

Keyboard Text Input Line 3

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

This statement constructs the object input of the BufferedReader class. input will be in charge of handling the data that users enter at the keyboard during program execution.

Page 9: Chapter 11 Slides

Keyboard Text Input Line 4

System.out.print("Enter Name ===>> ");

This statement provides a prompt for the program user prior to the statement that expects user keyboard input.

Page 10: Chapter 11 Slides

Keyboard Text Input Line 5

Name = input.readLine();

input is an object of the BufferedReader class. readLine is one of its methods. This statement stops program execution and waits for user input from the keyboard.

Page 11: Chapter 11 Slides

Keyboard Text Input Line 6

System.out.print("Enter Age ===>> ");age = Integer.parseInt(input.readLine());

The input.readLine statement is used to stop program execution and wait for user input. This time the statement is more complex. Numeric input is requested and readLine can only digest string input. Recall that Integer.parseInt can convert string data to numeric Integer data.

Page 12: Chapter 11 Slides

Keyboard Text Input Line 7

System.out.print("Enter GPA ===>> ");gpa = Double.parseDouble(input.readLine());

Line 7 presents nothing new. This is now a repetition of the keyboard prompt followed by keyboard input that is converted. In this case the string input is converted to a Double type.

Page 13: Chapter 11 Slides

#1 Start by adding the Input/Output Java package:Import java.io.*;

#2 Alter the main method method by usingpublic static void main (String args[]) throws IOException

#3 Define a BufferedReader object for program inputBufferedReader input =

new BufferedReader(newInputStreamReader(System.in));

#4 Provide a user prompt likeSystem.out.print("Enter Age ===>> ");

#5 Get user input and convert string input if necessary:age = Integer.parseInt(input.readLine());

Keyboard Text Input Summary

Page 14: Chapter 11 Slides

The for loop is ideal for loop structures that repeat some process a known - or fixed - number of times.

When to Use the <for> Loop

Page 15: Chapter 11 Slides

The while loop structure needs to be used when a condition must be checked before even a single loopbody is executed.

When to Use the <while> Loop

Page 16: Chapter 11 Slides

The do..while loop structure needs to be used when the loop body must be executed at least once.

When to Use the <do..while> Loop

Page 17: Chapter 11 Slides

Program loop structures frequently use variables that sum-up entered values. Such a variable is called an accumulator.

Make sure that the accumulator is initialized before it is used inside the loop structure.

This is one of many reasons why OOP adds reliability to programming. The use of classes with constructors can insure that all data fields in an object are properly initialized when a new object of a class is instantiated.

Initialize Your Accumulators

Page 18: Chapter 11 Slides

// Java1104.java// This program computes the average for a fixed set of grades using a for loop. import java.io.*;public class Java1104{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int k; // loop counter

int count; // quantity of entered gradesint grade; // individually entered gradeint sum = 0; // sum of entered gradesdouble mean; // average of entered gradesSystem.out.print("Enter grade count ===>> ");count = Integer.parseInt(input.readLine());for (k = 1; k <= count; k++){

System.out.print("Enter grade ===>> ");grade = Integer.parseInt(input.readLine());sum += grade;

}mean = (double) sum / count;System.out.println("Average Grade: " + mean);

}}

Java1104.java Output

How many grades will be averaged ===>> 5Enter grade ===>> 60Enter grade ===>> 70Enter grade ===>> 80Enter grade ===>> 90Enter grade ===>> 100

Grade average: 80

Page 19: Chapter 11 Slides

// Java1105.java// This program computes the average for an unknown quantity of// grades using a while loop. This example produces a logic error, which// is best seen by entering the same set of numbers.import java.io.*;public class Java1105{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));int count = 0; // quantity of entered gradesint grade = 0; // individually entered gradeint sum = 0; // sum of entered gradesdouble mean; // average of entered grades

while (grade != -999){

System.out.print("Enter grade ===>> ");grade = Integer.parseInt(input.readLine());count++;sum += grade;

}

System.out.println();mean = (double) sum / count;System.out.println("Average Grade: " + mean);

}}

Java1105.java Output

Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> -999

Average Grade: -83.16666666666667

Page 20: Chapter 11 Slides

// Java1106.java// This program computes the average for an unknown quantity of grades using a while loop, and fixes the // logic problem of the previous program example with a conditional statement.import java.io.*;public class Java1106{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int count = 0; // quantity of entered grades

int grade = 0; // individually entered gradeint sum = 0; // sum of entered gradesdouble mean; // average of entered gradeswhile (grade != -999){

System.out.print("Enter grade ===>> ");grade = Integer.parseInt(input.readLine());if (grade != -999){

count++; // counter sum += grade; // accumulator

}} System.out.println();mean = (double) sum / count;System.out.println("Average Grade: " + mean);

}}

Java1106.java Output

Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> 100Enter grade ===>> -999

Average Grade: 100.0

Page 21: Chapter 11 Slides

// Java1107.java// This program computes the average with a do..while loop.import java.io.*;public class Java1107{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); int count = 0; // quantity of entered grades

int grade = 0; // individually entered gradeint sum = 0; // sum of entered gradesdouble mean; // average of entered gradesdo {

System.out.print("Enter grade ===>> ");grade = Integer.parseInt(input.readLine());if (grade != -999){

count++; // counter sum += grade; // accumulator

}} while (grade != -999); System.out.println();mean = (double) sum / count;System.out.println("Average Grade: " + mean);

}}

Java1107.java Output

Enter grade ===>> 60Enter grade ===>> 70Enter grade ===>> 80Enter grade ===>> 90Enter grade ===>> 100Enter grade ===>> -999

Grade average: 80

Page 22: Chapter 11 Slides

The while loop and do...while loop are ideally used for repetition that depends on a certain condition to be true.This is not necessarily a counting condition. The loop may exit when a certain value is entered and the loop condition becomes true.

Flag is the term used in computer science to detect if a certain value is entered or altered to change the loop exit condition. The value that is entered or altered is called the Flag.

<while> and <do..while> Need a Flag

Page 23: Chapter 11 Slides

// Java1108.java// This program demonstrates nested one-way selection.import java.io.*;

public class Java1108{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));double bonus = 500; // year-end employee bonusdouble sales; // yearly salesint years; // years worked with company

System.out.print("Enter yearly sales ===>> ");sales = Double.parseDouble(input.readLine()); if (sales >= 250000){

System.out.println("Your bonus will be increased by $1000.00"); bonus += 1000;System.out.print("Enter years worked with the company ===>> ");years = Integer.parseInt(input.readLine());if (years > 10){

System.out.println("Your bonus will be increased by $250.00");bonus += 250;

}}System.out.println();System.out.println("Your year-end bonus will be: $" + bonus);

}}

Java1108.java Output #1

Enter your yearly sales ===>> 300000

Your bonus will be increased by $1000.00Enter years worked with the company ===>> 15Your bonus will be increased by $250.00

Your year-end bonus will be: 1750

Java1108.java Output #2

Enter your yearly sales ===>> 500000

Your bonus will be increased by $1000.00Enter years worked with the company ===>> 5

Your year-end bonus will be: 1500

Java1108.java Output #3

Enter your yearly sales ===>> 100000

Your year-end bonus will be: 500

Page 24: Chapter 11 Slides

// Java1109.java// This program displays an admission message based on an entered// SAT score. It also determines financial need with a nested if...else structure.

import java.io.*;

public class Java1109{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));int sat;double income;System.out.print("Enter your SAT score ===>> ");sat = Integer.parseInt(input.readLine());if (sat >= 1100){

System.out.println("You are admitted");System.out.print("Enter your family income ===>> ");income = Double.parseDouble(input.readLine());if (income <= 20000)

System.out.println("You will receive financial aid");else

System.out.println("You will not receive financial aid");}else{

System.out.println("You are not admitted");}

}}

Java1109.java Output #1

Enter your SAT score ===>> 1500

You are admitted

Enter your family income ===>> 10000

You will receive financial aid

Java1109.java Output #2

Enter your SAT score ===>> 1200

You are admitted

Enter your family income ===>> 75000

You will not receive financial aid

Java1108.java Output #3

Enter your SAT score ===>> 800

You are not admitted

Page 25: Chapter 11 Slides

// Java1110.java// This program assigns grades 'A'..'F' based on numerical scores using multiple nested if..else statements.

import java.io.*;

public class Java1110{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));double score;char grade;

System.out.print("Enter your numerical score ===>> ");score = Double.parseDouble(input.readLine());if (score >= 90.0)

grade = 'A';else if (score >= 80.0)

grade = 'B';else if (score >= 70.0)

grade = 'C';else if (score >= 60.0)

grade = 'D';else

grade = 'F';

System.out.println("Your grade will be: " + grade); }

}

Java1110.java Output #1

Enter your numerical score ===>> 100Your grade will be: A

Java1110.java Output #2

Enter your numerical score ===>> 90.5Your grade will be: A

Java1110.java Output #3

Enter your numerical score ===>> 83.756Your grade will be: B

Java1110.java Output #4

Enter your numerical score ===>> 79.999Your grade will be: C

Java1110.java Output #5

Enter your numerical score ===>> 60Your grade will be: D

Java1110.java Output #6

Enter your numerical score ===>> 59.999Your grade will be: F

Page 26: Chapter 11 Slides

Output for Java1111.java, Java1112.java and Java1113.java

1 * 11 = 112 * 11 = 223 * 11 = 334 * 11 = 445 * 11 = 55

1 * 12 = 122 * 12 = 243 * 12 = 364 * 12 = 485 * 12 = 60

1 * 13 = 132 * 13 = 263 * 13 = 394 * 13 = 525 * 13 = 65

Page 27: Chapter 11 Slides

// Java1111.java// This program displays several multiplication tables using// nested <for> loop structures.

public class Java1111{

public static void main(String args[]){

for (int table = 11; table <= 13; table++){

for (int k = 1; k <= 5; k++){

System.out.println(k + " * " + table + " = " + k * table);}System.out.println();

}}

}

Page 28: Chapter 11 Slides

// Java1112.java// This program displays several multiplication tables using// nested pre-condition <while> loop structures.public class Java1112{

public static void main(String args[]){

int k = 1;int table = 11;while (table <= 13){

while (k <= 5){

System.out.println(k + " * " + table + " = " + k * table);k++;

}System.out.println();k = 1;table++;

}}

}

Page 29: Chapter 11 Slides

// Java1113.java// This program displays several multiplication tables using// nested post-condition <do..while> loop structures.

public class Java1113{

public static void main(String args[]){

int k = 1;int table = 11;do {

do{

System.out.println(k + " * " + table + " = " + k * table);k++;

}while (k <= 5);System.out.println();k = 1;table++;

}while (table <= 13);

}}

Page 30: Chapter 11 Slides

The program style of control structures varies considerably. Two different styles will be shown here with <do...while>, which shows a general pattern of choosing more clarity or choosing less space.

Control Structure Style

Page 31: Chapter 11 Slides

do { do { System.out.println(k + " * " + table + " = " + k * table); k++; } while (k <= 5); System.out.println(); k = 1; table++;}while (table <= 13);

Style 1

Page 32: Chapter 11 Slides

do { do { System.out.println(k + " * " + table + " = " + k * table); k++; } while (k <= 5); System.out.println(); k = 1; table++;} while (table <= 13);

Style 2

Page 33: Chapter 11 Slides

// Java1114.java// This program demonstrates compound decisions with the logical or ( || ) operator.

import java.io.*;

public class Java1114{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));int education; // years of educationint experience; // years of work experience

System.out.print("Enter years of education ===>> ");education = Integer.parseInt(input.readLine());System.out.print("Enter years of experience ===>> ");experience = Integer.parseInt(input.readLine());

if ((education >= 16) || (experience >= 5))System.out.println("You are hired");

elseSystem.out.println("You are not qualified");

}}

Java1114.java Output #1

Enter years of education ===>> 17Enter years of experience ===>> 8You are hired

Java1114.java Output #2

Enter years of education ===>> 17Enter years of experience ===>> 2You are hired

Java1114.java Output #3

Enter years of education ===>> 13Enter years of experience ===>> 8You are hired

Java1114.java Output #4

Enter years of education ===>> 13Enter years of experience ===>> 2You are not qualified

Page 34: Chapter 11 Slides

// Java1115.java// This program demonstrates compound decisions with the logical and ( && ) operator.

import java.io.*;

public class Java1115{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));int education; // years of educationint experience; // years of work experience

System.out.print("Enter years of education ===>> ");education = Integer.parseInt(input.readLine());System.out.print("Enter years of experience ===>> ");experience = Integer.parseInt(input.readLine());

if ((education >= 16) && (experience >= 5))System.out.println("You are hired");

elseSystem.out.println("You are not qualified");

}}

Java1115.java Output #1

Enter years of education ===>> 17Enter years of experience ===>> 8You are hired

Java1115.java Output #2

Enter years of education ===>> 17Enter years of experience ===>> 2You are not qualified

Java1115.java Output #3

Enter years of education ===>> 13Enter years of experience ===>> 8You are not qualified

Java1115.java Output #4

Enter years of education ===>> 13Enter years of experience ===>> 2You are not qualified

Page 35: Chapter 11 Slides

Java uses || to indicate a logical or.

Java uses && to indicate a logical and.

Java uses ! to indicate a logical not.

Java Logical Operators

Page 36: Chapter 11 Slides

// Java1116.java// This program demonstrates compound decision with a do...while loop.// The program checks for proper data entry. The <equals> String method// is used to compare the string values.

import java.io.*;

public class Java1116{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String gender;

do{

System.out.print("Enter your Gender [M/F] ===>> ");gender = input.readLine();

}while (!( gender.equals("M") || gender.equals("F") ));

System.out.println("Your gender is " + gender);

}}

Java1116.java Output

Enter your Gender [M/F] ===>> QEnter your Gender [M/F] ===>> tEnter your Gender [M/F] ===>> 1Enter your Gender [M/F] ===>> fEnter your Gender [M/F] ===>> mEnter your Gender [M/F] ===>> FYour gender is F

Page 37: Chapter 11 Slides

// Java1117.java// This program demonstrates compound decision with a do...while loop.// The program does not work properly because of misplaced parentheses.

import java.io.*;

public class Java1117{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String gender;

do{

System.out.print("Enter your Gender [M/F] ===>> ");gender = input.readLine();

}while (!(gender.equals("M")) || gender.equals("F") );

System.out.println("Your gender is " + gender);

}}

Java1117.java Output

Enter your Gender [M/F] ===>> DEnter your Gender [M/F] ===>> QEnter your Gender [M/F] ===>> FEnter your Gender [M/F] ===>> M

Your gender is M

Page 38: Chapter 11 Slides

Correct

while ( !( Gender.equals("M") || Gender.equals("F") ) );

Incorrect

while ( !(Gender.equals("M") ) || Gender.equals("F") );

Watch Your Parentheses

Page 39: Chapter 11 Slides

// Java1118.java// This program demonstrates incorrect use of negative compound// decision structure. There will never be correct input.

import java.io.*;

public class Java1118{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String gender;

do{

System.out.print("Enter your Gender [M/F] ===>> ");gender = input.readLine();

}while (!(gender.equals("M")) || !(gender.equals("F")) );

System.out.println("Your gender is " + gender);}

}

Java1118.java Output

Enter your gender [M/F] ===>> DEnter your gender [M/F] ===>> QEnter your gender [M/F] ===>> FEnter your gender [M/F] ===>> MEnter your gender [M/F] ===>> fEnter your gender [M/F] ===>> m........

Loop never exits. No value satisfies the compound condition.

Page 40: Chapter 11 Slides

not(A or B) is equivalent to not(A) and not(B)

not(A and B) is equivalent to not(A) or not(B)

De Morgan’s Law

Page 41: Chapter 11 Slides

// Java1119.java// This program demonstrates correct use of negative compound// decision structure using DeMorgan's Law.

import java.io.*;

public class Java1119{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String gender;

do{

System.out.print("Enter your Gender [M/F] ===>> ");gender = input.readLine();

}

while (!(gender.equals("M")) && !(gender.equals("F")) );System.out.println("Your gender is " + gender);

}}

Java1119.java Output #1

Enter your Gender [M/F] ===>> QEnter your Gender [M/F] ===>> WEnter your Gender [M/F] ===>> M

Your Gender is M

Java1119.java Output #2

Enter your Gender [M/F] ===>> F

Your Gender is F

Page 42: Chapter 11 Slides

// Java1120.java// This program demonstrates using a boolean data type// with an input protection loop to add readability to a program.

import java.io.*;

public class Java1120{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String gender;boolean correct;do{

System.out.print("Enter your Gender [M/F] ===>> ");gender = input.readLine();correct = (gender.equals("M")) || (gender.equals("F"));if (!correct)

System.out.println("Incorrect input; please re-enter");}while (!correct);System.out.println();System.out.println("Your gender is " + gender);

}}

Java1120.java Output #1

Enter your Gender [M/F] ===>> qIncorrect input; please re-enterEnter your Gender [M/F] ===>> QIncorrect input; please re-enterEnter your Gender [M/F] ===>> 1Incorrect input; please re-enterEnter your Gender [M/F] ===>> mIncorrect input; please re-enterEnter your Gender [M/F] ===>> M

Your gender is M

Java1120.java Output #2

Enter your Gender [M/F] ===>> F

Your Gender is F

Page 43: Chapter 11 Slides

// Java1121.java// This program accepts upper-case as well as lower-case.// Gender input for [M/F] by using multiple conditional statements.import java.io.*;public class Java1121{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String gender;boolean correct;do{

System.out.print("Enter your Gender [M/F] ===>> ");gender = input.readLine();correct = (gender.equals("M")) || (gender.equals("F")) ||

(gender.equals("m")) || (gender.equals("f"));if (!correct)

System.out.println("Incorrect input; please re-enter");}while (!correct);System.out.println();System.out.println("Your gender is " + gender);

}}

Java1121.java Output #1

Enter your Gender [M/F] ===>> qIncorrect input; please re-enterEnter your Gender [M/F] ===>> QIncorrect input; please re-enterEnter your Gender [M/F] ===>> 1Incorrect input; please re-enterEnter your Gender [M/F] ===>> M

Your gender is M

Java1121.java Output #2

Enter your Gender [M/F] ===>> F

Your gender is F

Java1121.java Output #3

Enter your Gender [M/F] ===>> m

Your gender is m

Java1121.java Output #4

Enter your Gender [M/F] ===>> f

Your gender is f

Page 44: Chapter 11 Slides

// Java1122.java// This program shows the need for a practical compound condition// used with an input protection loop.// The program requests the user PIN, but rejects access after three tries.import java.io.*;public class Java1122{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));String pin;int tries = 0;do{

System.out.print("Enter your PIN ===>> ");pin = input.readLine();tries++;

}while (!pin.equals("8423") && (tries <= 3));if (tries > 4)

System.out.println("You have exceeded your PIN entries");else

System.out.println("Your PIN is accepted");}

}

Java1122.java Output #1

Please enter your PIN ===>> 4325Please enter your PIN ===>> 4326Please enter your PIN ===>> 4327Please enter your PIN ===>> 4328You have exceeded your PIN entries

Java1122.java Output #2

Please enter your PIN ===>> 4325Please enter your PIN ===>> 4326Please enter your PIN ===>> 8423Your PIN is accepted

Page 45: Chapter 11 Slides

You will see <do..while> used frequently for input protectionloops.

The post-condition loop makes sense for checking erroneous input because you want the program to enter the loop body at least one time.

do…while and Input Protection

Page 46: Chapter 11 Slides

A and ( (A or B) and (B or C) and (A or C) or ((B and C) or (A and B)))

This statement is false whenever the first A is false.

In such a situation it is not necessary to check the remainder of the statement.

Short-Circuiting with and

Page 47: Chapter 11 Slides

A or ( (A or B) and (B or C) and (A or C) or ((B and C) or (A and B)))

This statement is true whenever the first A is true.

In such a situation it is not necessary to check the remainder of the statement.

Short-Circuiting with or

Page 48: Chapter 11 Slides

// Java1123.java// This program uses "short circuiting" but it is not noticeable at all.

import java.io.*;

public class Java1123{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));System.out.print("Enter number 1 ===>> ");int n1 = Integer.parseInt(input.readLine());System.out.print("Enter number 2 ===>> ");int n2 = Integer.parseInt(input.readLine());

if (n1 % 2 == 0 && n2 % 2 == 0)System.out.println("Both numbers are even");

elseSystem.out.println("Both numbers are not even");

}}

Java1123.java Output #1

Enter number 1 ===>> 12Enter number 2 ===>> 24Both numbers are even

Java1123.java Output #2

Enter number 1 ===>> 12Enter number 2 ===>> 15Both numbers are not even

Java1123.java Output #3

Enter number 1 ===>> 15Enter number 2 ===>> 31Both numbers are not even

Page 49: Chapter 11 Slides

You have seen return methods that return integers and real numbers. Method isEven returns true or false, since it is a boolean return method. The purpose of the method is to return true if the method argument number is even and false if number is odd. It also generates output so we can see that the method was called. The purpose of this method is to help explain short circuiting in the next couple program examples.

The isEven Method

public static boolean isEven(int Number) { System.out.println(); System.out.println("Calling isEven Method"); System.out.println(); if (Number % 2 == 0) return true; else return false; }

Page 50: Chapter 11 Slides

// Java1124.java// This program uses "short circuiting" and uses the isEven// method to demonstrate short circuiting with logical or.

import java.io.*;

public class Java1124{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));System.out.print("Enter number 1 ===>> ");int n1 = Integer.parseInt(input.readLine());System.out.print("Enter number 2 ===>> ");int n2 = Integer.parseInt(input.readLine());if (isEven(n1) || isEven(n2))

System.out.println("One or more numbers are even");else

System.out.println("Neither numbers are even");}

public static boolean isEven(int number){

System.out.println();System.out.println("Calling isEven Method");System.out.println();if (number % 2 == 0)

return true;else

return false;}

}

Java1124.java Output #1

Enter number 1 ===>> 12Enter number 2 ===>> 24

Calling IsEven Method

One or more numbers are even

Java1124.java Output #2

Enter number 1 ===>> 12Enter number 2 ===>> 15

Calling IsEven Method

One or more numbers are even

Java1124.java Output #3

Enter number 1 ===>> 15Enter number 2 ===>> 31

Calling isEven Method

Calling isEven Method

Neither numbers are even

Page 51: Chapter 11 Slides

// Java1125.java// This program uses "short circuiting" and uses the isEven// method to demonstrate short circuiting with logical and.

import java.io.*;

public class Java1125{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));System.out.print("Enter number 1 ===>> ");int n1 = Integer.parseInt(input.readLine());System.out.print("Enter number 2 ===>> ");int n2 = Integer.parseInt(input.readLine());if (isEven(n1) && isEven(n2))

System.out.println("Both numbers are even");else

System.out.println("Both numbers are not even");}

public static boolean isEven(int number){

System.out.println();System.out.println("Calling IsEven Method");System.out.println();if (number % 2 == 0)

return true;else

return false;}

}

Java1125.java Output #1

Enter number 1 ===>> 12Enter number 2 ===>> 24

Calling isEven Method

Calling isEven Method

Both numbers are even

Java1125.java Output #2

Enter number 1 ===>> 12Enter number 2 ===>> 25

Calling isEven Method

Calling isEven Method

Both numbers are not even

Java1125.java Output #3

Enter number 1 ===>> 15Enter number 2 ===>> 31

Calling isEven Method

Both numbers are not even

Page 52: Chapter 11 Slides

Recursion is the process of a method calling itself.

Recursion Definition

Page 53: Chapter 11 Slides

// Java1126.java// This program introduces recursion as an alternative to repetition.// This example creates an infinite loop.

public class Java1126{

public static void main(String args[]){

count();}

private static int x = 1000;

public static void count(){

x++;System.out.println("x = " + x);count();

}

}

Java1126.java Output

X = 1001X = 1002X = 1003X = 1004X = 1005X = 1006X = 1007X = 1008X = 1009X = 1010........

DOES NOT END

Page 54: Chapter 11 Slides

It is easy to write programs with recursive methods thatrepeat in an infinite pattern of recursive calls. Some special condition must be tested before each recursive call is made.

Recursion Warning

Page 55: Chapter 11 Slides

// Java1127.java// This program introduces recursion as an alternative to repetition. The // Count method includes a conditional statement to end the recursive calls.

public class Java1127{

public static void main(String args[]){

count();}

private static int x = 1000;

public static void count(){

x++;System.out.println("x = " + x);if (x < 1200)

count();}

}

Java1127.java Output

X = 1001X = 1002X = 1003X = 1004X = 1005X = 1006X = 1007X = 1008X = 1009.........

X = 1197X = 1198X = 1199X = 1200

Page 56: Chapter 11 Slides

Recursion is the process of a method calling itself.

Recursion simulates repetition.

Recursion requires some condition that exits the recursive calling to prevent infinite repetition. The variable value that makes the condition true and stops the recursive calls is called the base case or exit

You will find in some future topics that there exist a variety of programming problems that are easier to solve with recursive structures than with iterative loop structures.

Recursion Notes

Page 57: Chapter 11 Slides

The exercises that follow will be in the same pattern as the exercises presented in previous chapters. Each exercise presents a brief program with the mission to determine the program output. The essence of the exercise revolves around tracing the variable values as they change during program execution. This time the exercises will be more challenging with the addition of nested control structures and compound conditions.

The question in all of these is “What is the output of this program?”

Worked-Out Exercises

Page 58: Chapter 11 Slides

// EX1101.java

public class Ex1101{ public static void main(String args[]) { for (int x = 1; x < 2; x++) for (int y = 1; y < 3; y++) System.out.println(x + " " + y); }} Ex1101.java Answer

x y Output

1 1 1 11 2 1 2

Page 59: Chapter 11 Slides

// Ex1102.java

public class Ex1102{

public static void main(String args[]){

for (int x = 1; x < 3; x++){

for (int y = 1; y < 4; y++)System.out.print(x*y + " ");

System.out.println();}

}}

Ex1102.java Answer

x y Output

1 1 11 2 1 21 3 1 2 32 1 22 2 2 42 3 2 4 6

Page 60: Chapter 11 Slides

// Ex1103.java

public class Ex1103{

public static void main(String args[]){

int x = 5;int k,y;while (x <= 8){

y = 1;while (y <= 7){

y++;k = x + y;System.out.println(y + " " + k);

}x += y;System.out.println("x = " + x);

} }

}

Ex1103.java Answer

y k x Output5

12 73 84 95 106 117 128 13 13

k = 13

Page 61: Chapter 11 Slides

An OBOB is an Off By One Bug error.

This problem occurs at the boundaries of control structures.

Carefully check your program code at the boundaries to avoid OBOBs.

OBOB Warning!

Page 62: Chapter 11 Slides

// Ex1104.java

public class Ex1104{

public static void main(String args[]){

int a = 1, b = 2, c = 3, d = 4;while (a < b && c < d){

a = c + d;c = a + b;

}System.out.println(a + b + c + d);

}}

Ex1104.java Answer

a b c d Output1 2 3 47 9

7294

Page 63: Chapter 11 Slides

// Ex1105.java

public class Ex1105{

public static void main(String args[]){

int a;int b = 2;for (int k = 0; k < 4; k++){

a = k;b += k;while (a < b){

System.out.println(a + " " + b);a += b;b += k;

}}

}}

Ex1105.java Answer

k a b Output2

0 0 2 0 22 2

1 1 3 1 3 4 42 2 6 2 6

8 83 3 11 3 11

14 14

Page 64: Chapter 11 Slides

// Ex1106.java

public class Ex1106{

public static void main(String args[]){

int a = 0;int b = 10;for (int k = a; k < b; k++){

a++;b--;System.out.println(a + " " + b + " " + k);

}}

}

Ex1106.java Answer

k a b Output

0 100 1 9 1 9 01 2 8 2 8 12 3 7 3 7 23 4 6 4 7 34 5 5 5 5 4 5

Page 65: Chapter 11 Slides

// Ex1107.java

public class Ex1107{

public static void main(String args[]){

int t = 0;for (int p = 1; p <= 4; p++)

for (int q = 1; q <= 4; q++)t++;

System.out.println("t = " + t);}

}

Ex1107.java Answer

p q t Output0

1 1 12 23 34 4

2 1 52 63 74 8

3 1 92 103 114 12

4 1 132 143 154 16

t = 16

Page 66: Chapter 11 Slides

// Ex1108.java

public class Ex1108{

public static void main(String args[]){

int t = 0;for (int p = 0; p < 10; p++)

for (int q = 1; q < 10-p; q++)t++;

System.out.println("t = " + t);}

}

Ex1108.java Answer

p q t Output0

0 1 12 23 34 45 56 67 78 89 9

1 1 102 113 124 135 146 157 168 17

2 1 182 193 204 215 226 237 24

3 1 252 263 274 285 296 30

4 1 312 323 334 345 35

5 1 362 373 384 39

6 1 402 413 42

7 1 432 44

8 1 45

t = 45

Page 67: Chapter 11 Slides

// Ex1109.CPP

public class Ex1109{

public static void main(String args[]){

int n1, n2, n3;n1 = n2 = n3 = 1;for (int k = 3; k <= 10; k++){

n3 = n1 + n2;n1 = n2;n2 = n3;

}System.out.println("n3 = " + n3);

}}

Ex1109.java Answer

k n3 n1 n2 Output1 1 1

3 2 1 24 3 2 35 5 3 56 8 5 87 13 8 138 21 13 219 34 21 3410 55 34 55

n3 = 55

Page 68: Chapter 11 Slides

// Ex1110.java

public class Ex1110{

public static void main(String args[]){

int a = 5;int b = 10;int c = 13;while (a < b && b != c){

a += 2;b++;if ((a + b) % 2 == 0)

c++;}System.out.println(a + " " + b + " " + c);

}}

Ex1110.java Answer

a b c a < b b != c Output5 10 13 true true7 11 14 true true9 12 true true11 13 15 true true13 14 true true15 15 16 false true

15 15 16

Page 69: Chapter 11 Slides

// Ex1111 THE MYSTERY PROGRAMimport java.io.*;public class Ex1111{

public static void main (String args[]) throws IOException{

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));int a, b , c;System.out.print("Enter integer 1 ===>> ");a = Integer.parseInt(input.readLine());System.out.print("Enter integer 2 ===>> ");b = Integer.parseInt(input.readLine());if (a < b)

if (b < a)c = 1000;

elsec = 2500;

elseif (b > a)

c = 2000;else

c = 2500;System.out.println("c = " + c);

}}

Ex1111.java Answer

a b c Output? ? ? C = 2500

Page 70: Chapter 11 Slides

// Ex1112.java

public class Ex1112{

public static void main(String args[]){

for (int x = 1; x <= 4; x++){

for (int y = 1; y <= 4; y++)System.out.print(x + y + " ");

System.out.println();}

}}

Ex1112.java Answer

x y x + y1 1 21 2 31 3 41 4 52 1 32 2 42 3 52 4 63 1 43 2 53 3 63 4 74 1 54 2 64 3 74 4 8

2 3 4 53 4 5 64 5 6 75 6 7 8

FINALOUTPUT