Page 487 - Introduction to Programming with Java: A Problem Solving Approach
P. 487
11.9 Short-Circuit Evaluation
This section supplements the && logical operator material you studied in Chapter 4, Section 4.4 and the || logical operator material you studied in Chapter 4, Section 4.5.
Consider the program in Figure 11.9. It calculates a basketball player’s shooting percentage and prints an associated message. Note the if statement’s heading, repeated here for your convenience. In particular, note the division operation with attempted in the denominator.
11.9 Short-Circuit Evaluation 453
/********************************************************************
*
ShootingPercentage.java
Dean & Dean
This program processes a basketball player’s shooting percentage.
********************************************************************/
*
*
*
import java.util.Scanner;
public class ShootingPercentage
{
public static void main(String[] args)
{
int attempted; // number of shots attempted
int made;
Apago PDF Enhancer
// number of shots made
Scanner stdIn = new Scanner(System.in);
System.out.print("Number of shots attempted: ");
attempted = stdIn.nextInt();
System.out.print("Number of shots made: ");
made = stdIn.nextInt();
if ((attempted > 0) && ((double) made / attempted) >= .5)
}
// end class ShootingPercentage
}
// end main
{
}
else
{
}
Sample session:
System.out.printf("Excellent shooting percentage - %.1f%%\n",
100.0 * made / attempted);
System.out.println("Practice your shot more.");
Number of shots attempted: 0
Number of shots made: 0
Practice your shot more.
Second sample session:
Number of shots attempted: 12
Number of shots made: 7
Excellent shooting percentage - 58.3%
If attempted is zero, division by zero does not occur.
Use %% to print a percent sign.
Figure 11.9 Program that illustrates short-circuit evaluation