java™ how to program, 10/e late objects version © copyright 1992-2015 by pearson education, inc....

161
Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Upload: britton-watson

Post on 20-Jan-2016

243 views

Category:

Documents


16 download

TRANSCRIPT

Page 1: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Java™ How to Program, 10/eLate Objects Version

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 2: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

vvv

Page 3: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Condition An expression that can be true or false.

if selection statement Allows a program to make a decision based on a condition’s value.

Equality operators (== and !=) Relational operators (>, <, >= and <=) Both equality operators have the same level of precedence,

which is lower than that of the relational operators. The equality operators associate from left to right. The relational operators all have the same level of

precedence and also associate from left to right.

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 4: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 5: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 6: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 7: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 8: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

An if statement always begins with keyword if, followed by a condition in parentheses. Expects one statement in its body, but may contain multiple

statements if they are enclosed in a set of braces ({}). The indentation of the body statement is not required, but it

improves the program’s readability by emphasizing that statements are part of the body.

Note that there is no semicolon (;) at the end of the first line of each if statement. Such a semicolon would result in a logic error at execution

time. Treated as the empty statement—semicolon by itself.

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 9: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 10: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 11: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 12: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 13: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 14: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Pseudocode If student’s grade is greater than or equal to 60 Then Display “Passed”

If the condition is false, the Display statement is ignored, and the next pseudocode statement in order is performed.

Indentation◦ Optional, but recommended◦ Emphasizes the inherent structure of structured programs

The preceding pseudocode If in Java:if ( studentGrade >= 60 ) System.out.println( "Passed" );

Corresponds closely to the pseudocode.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 15: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if statement flowchart diagram. Diamond, or decision symbol, indicates that a decision

is to be made. Workflow continues along a path determined by the

symbol’s guard conditions, which can be true or false. Each transition arrow emerging from a decision symbol

has a guard condition (in square brackets next to the arrow).

If a guard condition is true, the workflow enters the action state to which the transition arrow points.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 16: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 17: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if…else double-selection statement—specify an action to perform when the condition is true and another action when the condition is false.

PseudocodeIf student’s grade is greater than or equal to 60 Then Display “Passed”Else

Display “Failed” End If

The preceding If…Else pseudocode statement in Java:if ( grade >= 60 ) System.out.println( "Passed" );else System.out.println( "Failed" );

Note that the body of the else is also indented.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 18: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 19: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 20: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if…else statement flowchart diagram. The symbols in the UML activity diagram (besides the

initial state, transition arrows and final state) represent action states and decisions.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 21: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 22: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Block:◦ Compound statements with declarations◦ if (condition)◦ block or single statement◦ else ◦ block or signle statement

Do not put semicolumn after a block

Page 23: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Syntax errors◦ Caught by compiler

Run time error◦ Program fails during execution

Logic errors: ◦ Have their effect at execution time◦ Non-fatal: program runs, but has incorrect output◦ Fatal: program exits prematurely

Page 24: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Task: get grade of a student and display the message “you passed the course” if the grade is greater then or equal to 60

Page 25: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start 2a Display “Enter your grade: ” 2b Input grade 3 If grade >= 60 Display “You passed the course” Emd If 4 End

Page 26: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

// simple if import java.util.Scanner; //import Scanner class public class SimpleIf { // class block public static void main(String[] args) { // main method begins int grade; // variable decleration Scanner input = new Scanner(System.in); System.out.pritntf(“Enter your grade:”); grade = input.nextInt(); if (grade >= 60) System.out.printIn(“You passed the

course”); } // end main method } // end class SimpleIf

Page 27: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

// simple ifimport java.util.Scanner; //import Scannerclass public class SimpleIf { // class block public static void main(String[] args) { // main method begins int grade; // variable decleration Scanner input = new Scanner(System.in); System.out.pritntf(“Enter your

grade:”); grade = input.nextInt();

Page 28: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (grade >= 60) { // beginning of if block System.out.print(“You passed ”); System.out.println(“the course”); } // end of if block }// end of main method } // end of class

Page 29: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (condition) { statement1; statement2; .... } Example: if (grade > 60) { print the grade; print you passed the course; }

Page 30: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (condition) { expression1; // when the condition is true expression2; .... } else { expression1; // when the condition is false expression2; .... }

Page 31: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

If grade >= 60 Then Display you passed the course Display concratulationsElse Display you failed the course Display you have to take the course ageain End If

Page 32: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

// inside the main blockpublic static void main(String[] args){ int grade; System.out.pritntf(“Enter your grade:”); grade = input.netInt(); if (grade > 60) { System.out.printf(“You passed the course”); System.out.printf(“congraculations”); } else { System.out.printf(“You failed”); System.out.printf(“You have to take the course again”); } } // end method main

Page 33: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Task: ask the user to enter a real number calculate and display the square root of that

number if possible or display a message that square root can

not be taken

Page 34: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start2 Enter a real number3 if number is greater then 0 take its square root and display the square root else display a mesage that the number is less then 0, its

square root can not be taken4 End

Page 35: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start2a Declare Real number2b Declare Real squareRoot 3 input number4 if number >= 0 Then squareRoot = squareRoot(number) Display “the square root”, squareRoot Else Display “square root can not be taken “ End If5 End

Page 36: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

/* if ..else illustration import java.util.Scanner; public class SquareRoot { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.pritntf(“Enter a number:”); double number = input.nextDouble(); if (number>= 0.00) { double squareRoot = Math.sqrt(number); System.out.printf(“square root of %10.3f is %10.3f\n”,number,squareRoot); } else System.out. printf(“As the number is < 0 its square root can” “ not be computed”); }// end of main }// end of class

Page 37: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

double number = input.nextDouble(); Variable mumber is of type double

◦ A simple type for holding real valued variables

Page 38: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

nextDouble() nethod reads a double from keyboad◦ the execution stops ◦ The program weits the user to eneer soemthing

from keyboard◦ When the user press ENTER◦ nextDouble method converts the characters in ot

a double v◦ Assign to variable number on the left hand side of

assignment Number is declared in the same statement

Page 39: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

double squareRoot = Math.sqrt(number); Assignment statement Right hand side:

◦ Call sqrt method in Math class◦ Class_name.method_name◦ Takes the square root of the argument◦ What is send as an expressin

Left hand side◦ When the cvalue of right hand side is calculated◦ Assinged to variable squareRoot

Declaration and assignment in one statement

Page 40: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Task: get a real number from the user and display its inverse if the number if 0 display a mesage that inverse cannot be taken

Page 41: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start2 Declare Real number 3 Input number4 if number is zero Then Display “its inverse can not be computed” else Display “its inverse” , 1/x End if4 end

Page 42: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{ float number; // single presicion real type Scanner input = new Scanner(System.in); System.out.pritntf(“Enter a number:”); number = input.nextFloat(); if (number == 0.0) System.out.println(“a the number is zero its invers is infinity”);

else System.out.printf(“ inverse of %10.3f is %10.3f \n”,

number,1/number); } // end of main

Page 43: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

System.out.printf(“ inverse of %10.3f is %10.3f \n”, number,1/number); In total three arguments

◦ First: required the text of the message◦ Second. a float type variable◦ Third: 1/number, an expressin whose value can be

computed Inverse is computed without using a new variable This is not a recomanded programming style

◦ Readibility is lost◦ Inputing , processing and outputing should be seperated

as much as possible

Page 44: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Comparing real variables (float,double) with equal opperator is not recomanded

The representation of such numbers may be a bit different then their values

Ex:◦ 2.000 may be represented in memory as

2.00000001◦ 0.000 an exact zere may be as 0.0000001

So testing with == ◦ if (number == 0.0) may be false even numer is 0

Page 45: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Given a integer determine whether it is an odd or an even number

if the number is even it can be divided to 2 exactly number % 2 = 0 is true (number / 2 )*2 = number the two conditions are equivalent if the number is an odd one the condition is fales

Page 46: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{ int aNumber; Scanner input = new Scanner(System.in); System.out.pritntf(“Enter an integer:”); aNumber = input.nextInt(); if (aNumber % 2 == 0) System.out.printf(“%d is an even number\n”,aNumber);

else System.out.printf(“%d is an odd number \n”,aNumber);

}

Page 47: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{ int aNumber; Scanner input = new Scanner(System.in); System.out.pritntf(“Enter an integer:”); aNumber = inout.nextInt(); if ((aNumber / 2)*2 == aNumber) System.out.printf(“%d is an even number\n”,aNumber);

else System.out.printf(“%d is an odd number \n”,aNumber);

}

Page 48: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Can test multiple cases by placing if…else statements inside other if…else statements to create nested if…else statements.

Pseudocode:If student’s grade is greater than or equal to 90

Print “A”else

If student’s grade is greater than or equal to 80Print “B”

else If student’s grade is greater than or equal to 70

Print “C”else

If student’s grade is greater than or equal to 60 Print “D”

elsePrint “F”

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 49: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

This pseudocode may be written in Java asif (studentGrade >= 90) System.out.println("A");else if (studentGrade >= 80) System.out.println("B"); else if (studentGrade >= 70) System.out.println("C"); else if (studentGrade >= 60) System.out.println("D"); else System.out.println("F");

If studentGrade >= 90, the first four conditions will be true, but only the statement in the if part of the first if…else statement will execute. After that, the else part of the “outermost” if…else statement is skipped.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 50: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Most Java programmers prefer to write the preceding nested if…else statement as

if (studentGrade >= 90) System.out.println("A");else if (studentGrade >= 80) System.out.println("B");else if (studentGrade >= 70) System.out.println("C");else if (studentGrade >= 60) System.out.println("D");else System.out.println("F");

The two forms are identical except for the spacing and indentation, which the compiler ignores.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 51: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The Java compiler always associates an else with the immediately preceding if unless told to do otherwise by the placement of braces ({ and }).

Referred to as the dangling-else problem. The following code is not what it appears:

if (x > 5) if (y > 5) System.out.println("x and y are > 5");else System.out.println("x is <= 5");

Beware! This nested if…else statement does not execute as it appears. The compiler actually interprets the statement as

if (x > 5) if (y > 5) System.out.println("x and y are > 5"); else System.out.println("x is <= 5");

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 52: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

To force the nested if…else statement to execute as it was originally intended, we must write it as follows:

if (x > 5) { if (y > 5) System.out.println("x and y are > 5");}else System.out.println("x is <= 5");

The braces indicate that the second if is in the body of the first and that the else is associated with the first if.

Exercises 3.27–3.28 investigate the dangling-else problem further.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 53: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The if statement normally expects only one statement in its body. To include several statements in the body of an if (or the body of an else for an if…else statement), enclose the statements in braces.

Statements contained in a pair of braces form a block. A block can be placed anywhere that a single statement can be placed. Example: A block in the else part of an if…else statement:

if ( grade >= 60 ) System.out.println("Passed");else { System.out.println("Failed"); System.out.println("You must take this course again.");}

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 54: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Syntax errors (e.g., when one brace in a block is left out of the program) are caught by the compiler.

A logic error (e.g., when both braces in a block are left out of the program) has its effect at execution time.

A fatal logic error causes a program to fail and terminate prematurely.

A nonfatal logic error allows a program to continue executing but causes it to produce incorrect results.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 55: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 56: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Just as a block can be placed anywhere a single statement can be placed, it’s also possible to have an empty statement.

The empty statement is represented by placing a semicolon (;) where a statement would normally be.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 57: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 58: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Conditional operator (?:)—can be used in place of an if…else statement.

Ternary operator (takes three operands) Operands and ?: form a conditional expression Operand to the left of the ? is a boolean expression—evaluates to a boolean value (true or false)

Second operand (between the ? and :) is the value if the boolean expression is true

Third operand (to the right of the :) is the value if the boolean expression evaluates to false.

Example:System.out.println(studentGrade >= 60 ? "Passed" : "Failed");

Evaluates to the string "Passed" if the boolean expression studentGrade >= 60 is true and to the string "Failed" if it is false.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 59: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 60: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (condition1) statement of block of statements 1 else if (conditon2) statement of block of statements 2 else if (conditon3) statement of block of statements 3 else statement of block of statements 4

Page 61: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if condition1 is true statement 1 is performed other conditions are not cheked else if conditon2 is true statement 2 is performed other conditions are not cheked else if conditon3 is true statement 3 else none of the conditions 1,2,3 are true

statement 4 is performed

Page 62: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Task:given an integer determine and print whether it is a negative, zero or a positive number

Page 63: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

tghere are two conditions say c1: number > 0 c2: number < 0if (c1) number is positiveelse if (c2) number is negativeelse number is 0

Page 64: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

If number> 0 Then Display “number is positive”Else if ( number < 0) Display “number is negative”Else Display “number is zero” End If

Page 65: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

number is either: ◦ less then 0, equals to 0 or grater then 0◦ three posibilities are mutually exclusive◦ one of them and only one of them is true◦ the others are false◦ at the same time two of them cannot be ture

Page 66: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{ Scanner input = new Scanner(System.in); int mumber; number = input.nextInt(); if (number > 0) System.out.printf(“%d is a positve number”,number); else if (number < 0) System.out.printf(“%d is a negative number”,number);

else System.out.printf(“%d is zero”,number); } // end main method

Page 67: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (number> 0) Display “number is positive”if ( number < 0) Display “number is negative” if ( number = 0) Display “number is zero”

Page 68: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{ Scanner input = new Scanner(System.in); int mumber; number = input.nextInt(); if (number > 0) System.out.printf(“%d is a positve number”,number);

if (number < 0) System.out.printf(“%d is a negative number”,number);

if (number == 0) System.out.printf(“%d is zero”,number); }

Page 69: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Taking neagations of conditions c1 and c2 c1 number > 0 c1’ number <= 0 c2 number < 0 c2’ number >= 0if (c1’) { if (c2’) number is zero else number is negative } else number is positive

Page 70: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved
Page 71: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

ask two integers print whether

◦ first one is greater then the second◦ second one is greater or◦ they are equal

three mutually exclusive posibilities

Page 72: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{

int num1,num2;Sytetem.out.printf(“Enter first integers\n”);

num1 = input.netInt();Sytetem.out.printf(“Enter second integers\n”);

num2 = input.netInt();

Page 73: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (num1 > num2) Sytetem.out.printf(“first number is greater then seocnd \n”);

else if (num2>num1) Sytetem.out.printf(“second number is greater then first\n”);

else Sytetem.out.printf(“the two numbers are equal\n”);

} // end main method

Page 74: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

{

int num1,num2;Sytetem.out.printf(“Enter first integers\n”);

num1 = input.netInt();Sytetem.out.printf(“Enter second integers\n”);

num2 = input.netInt();

Page 75: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (num1 > num2) Sytetem.out.printf(“first number is greater\n”);

if (num2>num1) Sytetem.out. printf(“second number is greater\n”);

if (num2==num1) Sytetem.out.printf(“the two numbers are equal\n”);

} // end method main

Page 76: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

A retail store applies a progresive discount policy to its customers.

A progressively increasing discount means apply higer and higher discounts rates for

purchases. As the total sales increases progressively the customer pays less and less

Page 77: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

total sales, <= 100 no discount 100 <sales, <= 200 %10 discount 200 <sales, <= 400 %15 discount sales > 400, %20 discount Given a sales amount

◦ what is the amout of discout made ◦ and payment after the discount

based on the above discount rules

Page 78: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if sales is 50 TL◦ it is in the first slice: 0 < sales <= 100◦ no discount is made

if sales is 150 TL◦ it is in the second slice: 100 < sales <= 200◦ for the portion of the sales exceeding the lovwer

limit of 100, %10 discount is made so◦ discount = 0.1*(150 - 100) = 5 TL

Page 79: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if sales is 250 TL◦ it is in the third slice: 200 < sales <= 400◦ for the portion of the sales folling into the second

slice (100 < sales <=200), %10 is made,◦ for the remaining portion folling into the third

slice exceeding the lovwer limit of 200 %15 discount is made so

◦ discount = 0.1*(200 - 100) + 0.15*(250 - 200)◦ = 10 + 7.5 ◦ = 17.5 TL

Page 80: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if sales is 500 TL◦ it is in the forth slice: sales > 400◦ for the portion of the sales folling into the second slice

(100 < sales <=200), %10 is made,◦ for the portion of the sales folling into the third slice

(200 < sales <=400), %15 is made,◦ for the remaining portion folling into the forth slice

exceeding the lovwer limit of 400 %20 discount is made so

discount=0.1*(200-100)+0.15*(400-200)+0.2*(500-400)◦ = 10 + 30 + 20 ◦ = 50 TL

Page 81: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start 2 Enter base sales 3 if sales <= 100 discount = 0 else if sales <= 200 discount = 0.1*(sales - 100) else if sales <= 400 discount = 0.15*(sales - 200) + 0.1*100 else discount = 0.20*(sales - 400) + 0.15*200 +0.1*100 4 payment = sales - discount 5 print discout, payment 6 end

Page 82: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

double payment; double discount=0.0;//declare and initilize

double sale; System.out.printf(“Enter base sale:”);

sale= input.nextDouble();

Page 83: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if ( sale < = 100.0) discount = 0.0; else if (sale<= 200.0) discount = 0.1*(sale- 100.0); else if (sale<= 400) discount = 0.15*(sale- 200.0)+0.1*100.0;

else discount = 0.2*(sale- 400.0)+0.15*200.0+0.1*100.0;

Page 84: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

payment = sale – discount; System.out.printf(“actual payment: %f \n”,payment);

//...other output statements for printing discout

}

Page 85: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

i) Solve the same problem without using else◦ Only with simple if statements

ii) Improve the quality of the program by defining appropriate variables

iii) What is the limitation of the even improved program?◦ How can it be firther generalized?

Page 86: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Progressively accumulate the discount variablesSet discount = 0.0If the sales > 100 Then discount = 0.10*(sales - 100)End IfIf the sales > 200 Then discount = discount + (0.15-0.10)*(sales - 200)End IfIf the sales > 400 Then discount = discount + (0.20-0.15)*(sales - 400)End If

Page 87: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Income tax is progressively increases in a similar maner◦ As your income increases you pay progressively

higher and hgiher taxes An employee may get commusions from the

sales she made subject to progressively increasing commusion rates

In a contest the contester gets higher payments as she answers more and more questions

Still other examples can be found...

Page 88: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Get a grade between 0-100 Convert in to letter grade as follows:

◦ 80-100 A◦ 60-79 B◦ 40-59 C◦ 0-39 F

Page 89: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

int grade; // total grade System.out.printf(“Enter grade:”); grade = input.nextInt();

Page 90: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if (grade < 40) { System.out.printf(“you got F \n”); System.out.printf(“you have to take the course again\n”);} else if (grade < 60) { System.out.printf(“you got C \n”); System.out.printf(“you may take the course again optionally”);}else if (grade < 80) System.out.printf(“you got C \n”);else { Syste.out.printf(“you got A \n”); printf(“congraculations\n”);}

Page 91: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

given the coefficcients of a second order quadratic equation

ax2 + bx + c = 0 where a,b,c are coefficients find and print the real roots of the quadratic

equation Hint

◦ First compute delta where delta = b2-4ac

◦ Check the sign of delta delta < 0.0 no real root delta = 0.0 one real root delta > 0.0 two real roots

Page 92: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Java’s logical operators enable you to form more complex conditions by combining simple conditions.

The logical operators are ◦ && (conditional AND)◦ || (conditional OR)◦ & (boolean logical AND)◦ | (boolean logical inclusive OR)◦ ^ (boolean logical exclusive OR)◦ ! (logical NOT).

[Note: The &, | and ^ operators are also bitwise operators when they are applied to integral operands.]

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 93: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The && (conditional AND) operator ensures that two conditions are both true before choosing a certain path of execution.

Truth table shows all four possible combinations of false and true values for expression1 and expression2.

Java evaluates to false or true all expressions that include relational operators, equality operators or logical operators.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 94: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 95: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The || (conditional OR) operator ensures that either or both of two conditions are true before choosing a certain path of execution.

Figure 4.14 is a truth table for operator conditional OR (||).

Operator && has a higher precedence than operator ||. Both operators associate from left to right.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 96: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 97: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The parts of an expression containing && or || operators are evaluated only until it’s known whether the condition is true or false. T

This feature of conditional AND and conditional OR expressions is called short-circuit evaluation.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 98: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 99: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The boolean logical AND (&) and boolean logical inclusive OR (|) operators are identical to the && and || operators, except that the & and | operators always evaluate both of their operands (i.e., they do not perform short-circuit evaluation).

This is useful if the right operand has a required side effect—a modification of a variable’s value.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 100: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 101: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 102: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

A simple condition containing the boolean logical exclusive OR (^) operator is true if and only if one of its operands is true and the other is false.

If both are true or both are false, the entire condition is false.

Figure 4.15 is a truth table for the boolean logical exclusive OR operator (^).

This operator is guaranteed to evaluate both of its operands.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 103: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 104: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The ! (logical NOT, also called logical negation or logical complement) operator “reverses” the meaning of a condition.

The logical negation operator is a unary operator that has only one condition as an operand.

The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical negation operator) is false.

In most cases, you can avoid using logical negation by expressing the condition differently with an appropriate relational or equality operator.

Figure 4.16 is a truth table for the logical negation operator.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 105: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 106: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Figure 4.17 uses logical operators to produce the truth tables discussed in this section.

The %b format specifier displays the word “true” or the word “false” based on a boolean expression’s value.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 107: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 108: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 109: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 110: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 111: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 112: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 113: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved
Page 114: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Solve the letter grade problem in Exercise 3.8 using logical opperators

Algorithm:

Page 115: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start2 get grade3a If grade >=80 AND grade <= 100 Then Dlsplay “grade A”End If3b If grade >= 60 AND grade < 80 Dlsplay “grade B”End IfIf grade >=40 AND grade < 60 Then Dlsplay “grade C”End IfIf grade <= 0 AND grade < 40 Then Dlsplay “grade F”End If

Page 116: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

notice that only one of these conditions is satisfied◦ a numerical grade is either between 80-100◦ or between 60-79◦ and so on ...

only one of these simple if statements will be executed

Page 117: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

detecting whether a numerical value is within a specific range of values

useing the AND operator E.g.: variable x is in the range 20 – 40If x >= 20 AND x <= 40 Then Display “The value is inside the acceptable range”End IfElse Display “The value is outside the acceptable range”End If

Page 118: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

detecting whether a numerical value is outside a specific range of values

useing the OR operator E.g.: variable x is outside the range 20 – 40If x < 20 OR x > 40 Then Display “The value is outside in the acceptable

range”End If Else Display “The value is insde the acceptable range” End If

Page 119: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

If (x >= 20 && x <= 40 ) System.out.println(“The value is inside the

acceptable range”);else System.out.println(“The value is outside the

acceptable range”);

If ( x < 20 || x > 40 ) System.out.println( “The value is outside the

acceptable range”); else System.out.println(“The value is insde the

acceptable range”);

Page 120: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

A bank wants to decide wheter an applicant for credit is suitable or not

two criteria:◦ (1) enough salary: over 2000◦ (2) enough work experience: 2 year or more◦ otherwise the applicant will be rejected with

appropriate messages

Page 121: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

1 Start2 Declare Real salary yearsOnJob3a Display “Enter salary: ”3b Input salary4a Display “Enter years of working: ”4b Input yearsOnJob

Page 122: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

5 If salary >= 2000 Then If yearsOnJob >= 2 Then Dispay “your loan is approved” End If Else Display “You don’t have enough work

experience” End If Else Display “your income is not enough ” End If6 End

Page 123: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if ( salary >= 2000.0 ) if ( yearsOnJob >= 2 ) Sysgtem.out.priintln(“your loan is approved”); else // for the inner if Sysgtem.out.priintln (“You don’t have enough

work experience”);else // for the outer if Sysgtem.out.priintln(“your income is not

enough ”);

Page 124: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

This not the common structureif (condition1) statement1;else if (condition2) statement2;else Statement3;

Page 125: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

5 If salary >= 2000 AND yearsOnJob >= 2 Then Dispay “your loan is approved” End If Else Display “You loan is not approvced” End If Note: only two mesages to the applicant not explaining why she is rejected

Page 126: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if ( salary >= 2000.0 && yearsOnJob >= 2) Sysgtem.out.priintln(“your loan is

approved”);else Sysgtem.out.priintln (“You loan is not

approved ”);/* just two messges to the applicant appoved

or not without any explanation why she is not appoved */

Page 127: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if ( salary >= 2000.0 ) if ( yearsOnJob >= 2 ) Sysgtem.out.priintln(“your loan is approved”); else // for wich if inner or outer? Sysgtem.out.priintln (“You loan is not

approved”); /*for the inner if, because else belongs to the just

preceeding if statementWhat is the limitation of this code• /*• •

Page 128: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

if ( salary >= 2000.0 ){ if ( yearsOnJob >= 2 ) Sysgtem.out.priintln(“your loan is approved”);}else // for wich if inner or outer? Sysgtem.out.priintln (“You loan is not approved”); using braces we can control which if the else belongsWhat is the limitation of the code

Page 129: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Reformulate and code the loan applicant problem if only one of these condiitons is enough to be approved

Page 130: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Ask gender and age of a user and write message wheter he or she is to be retied or not

for males retirement age is 65 for females retirement age is 61

Page 131: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

while obtaining gender information use integers as such◦ gender: 1 female, 2 male

age an integer variableget gender and ageif age > 65 && gender is male then display a selective message for the male

about his retirement if age > 61 && gender is female then display a selective message for the female

about her retirement

Page 132: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

How would you shorten the code in case displaying the unique message for

both males and femalesİf( (age>65 && gender == 2) || (age>61 && gender == 1)) System.out.pritnln(“Shold reire“);

Page 133: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

University A accept grad students as follows◦ ALES at least 70 or GPA at least 3.00◦ AND interview at least 60 points◦ AND KPDS at least 70 or TOFEL at least 220

University B accept grad students as follows◦ ALES at least 60 or GPA at least 2.50◦ AND interview at least 60 points◦ AND KPDS at least 60 or TOFEL at least 180◦ AND no disiplinary punishments

University C accept grad students as follows◦ ALES at least 50 or GPA at least 2.25◦ AND interview at least 70 points◦ AND KPDS at least 80 or TOFEL at least 250

Page 134: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Ask an applicants her◦ ALES,,, KPDS, TOFEL scores◦ GPA and interview point◦ and whether took a disiplinary punishment or not

determine whether accepted by univeristy A, B or C

Develop Algorithm Pseudocode Flowchart Java code

Page 135: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Can take one of two values true or false. Used as flags In Java declared with keywork boolean E.g.: boolean isMale; isMale = true, // for a male boolean passedExam; passedExam = false; assigned constants true or false

Page 136: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Or values can be assinged as follows int grade; boolean passedExam; passedExam = grade >= 60; right hand side of the assignment is a conditional

expression whose value is true if grede variable has a value greater then or equal to 60.

its value is assigned to the boolean variable passedExam

after evaluating the assignemt the boolen variable is either true or false

Page 137: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

They can be used in if stfatementsif ( grade >= 60 || true ) always true no mather what grade isif ( false && true ) always false anding of two constants one being false boolean passedEnglish; passedEnglish = profGrade >= 60; boolean passedInter; passedInter = interScore >= 50; if (passedEngllish && passedInter) System.out.println(“you are accepted”);

Page 138: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

4.7 The switch Multiple-Selection Statement switch

◦ Useful when a variable or expression is tested for all the values it can assume and different actions are taken

Format◦ Series of case labels and an optional default caseswitch ( value ){

case '1':actionscase '2':actionsdefault:actions}

◦ break; exits from statement

 

Page 139: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

4.7 The switch Multiple-Selection Statement Flowchart of the switch statement

true

false

.

.

.

case a case a action(s) break

case b case b action(s) break

false

false

case z case z action(s) break

true

true

default action(s)

Page 140: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Forex Program with case #include <stdio.h> int main() { double ytl, double fxDol=1.35,fxEu =1.75,fxPo=2.5; int cont; printf(“1: dollar\n2: Euro\ 3: Pound\0:exit\n); scanf(“%d”,&cont);

while (cont !=0) { printf(“enter ytl:”); scanf(“%lf”,&ytl);

Page 141: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Forex Program with case switch (cont) { case 1: value = ytl/fxDol; printf(“dollar :%f\n”,value); break;

case 2: value = ytl/fxEu; printf(“euro:%f\n”,value); break;

case 3: value = ytl/fxPo printf(“pound:%f\n”,value); break:

default: printf(“You entred wrong number\n”); break:

} // end case

Page 142: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Forex Program with case printf(“1: dollar\n2: Euro\ 3: Pound\

0:exit\n); scanf(“%d”,&cont); } // end of while block } // end of main block

Page 143: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

switch multiple-selection statement performs different actions based on the possible values of a constant integral expression of type byte, short, int or char.

As of Java SE 7, the expression may also be a String.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 144: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 145: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 146: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 147: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 148: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 149: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 150: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The end-of-file indicator is a system-dependent keystroke combination which the user enters to indicate that there’s no more data to input.

On UNIX/Linux/Mac OS X systems, end-of-file is entered by typing the sequence

<Ctrl> d on a line by itself. This notation means to simultaneously press

both the Ctrl key and the d key. On Windows systems, end-of-file can be entered by typing

<Ctrl> z On some systems, you must press Enter after typing the end-of-

file key sequence. Windows typically displays the characters ^Z on the screen

when the end-of-file indicator is typed.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 151: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 152: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Scanner method hasNext determine whether there’s more data to input. This method returns the boolean value true if there’s more data; otherwise, it returns false.

Method hasNext returns false once the user types the end-of-file indicator.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 153: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

The switch statement consists of a block that contains a sequence of case labels and an optional default case.

The program evaluates the controlling expression in the parentheses following keyword switch.

The program compares this expression’s value (which must evaluate to an integral value of type byte, char, short or int, or to a String) with each case label.

If a match occurs, the program executes that case’s statements.

The break statement causes program control to proceed with the first statement after the switch.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 154: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

switch does not provide a mechanism for testing ranges of values—every value must be listed in a separate case label.

Each case can have multiple statements. switch differs from other control statements in that it does not

require braces around multiple statements in a case. Without break, the statements for a matching case and

subsequent cases execute until a break or the end of the switch is encountered. This is called “falling through.”

If no match occurs between the controlling expression’s value and a case label, the default case executes.

If no match occurs and there is no default case, program control simply continues with the first statement after the switch.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 155: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 156: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

Figure 4.10 shows the UML activity diagram for the general switch statement.

Most switch statements use a break in each case to terminate the switch statement after processing the case.

The break statement is not required for the switch’s last case (or the optional default case, when it appears last), because execution continues with the next statement after the switch.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 157: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 158: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 159: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 160: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.

Page 161: Java™ How to Program, 10/e Late Objects Version © Copyright 1992-2015 by Pearson Education, Inc. All Rights Reserved

When using the switch statement, remember that each case must contain a String or a constant integral expression.

An integer constant is simply an integer value. In addition, you can use character constants—specific

characters in single quotes, such as 'A', '7' or '$'—which represent the integer values of characters and enum constants.

The expression in each case can also be a constant variable—a variable that contains a value which does not change for the entire program. Such a variable is declared with keyword final.

Java has a feature called enum types. enum type constants can also be used in case labels.

© 1992-2015 by Pearson Education, Inc. All Rights Reserved.