Page 182 - Introduction to Programming with Java: A Problem Solving Approach
P. 182
148
Chapter 4 Control Statements
9.
Modify this program to avoid division by zero. Initialize a boolean variable called more with true, and use it as the while loop condition. Eliminate the prompt and input before the loop and move the prompt and input inside the loop to the top of the loop. Use an “if, else” structure in the loop to set more to false and bypass the normal calculation if the input is negative.
[after §4.13] Consider the following code fragment. Without changing the loop type, modify the code as follows. Incorporate an if statement in the loop body to prevent printout when the input equals the sentinel value of zero.
int x;
do
{
}
10.
[after §4.15] Here’s a brainteaser that uses Boolean logic:
You’re traveling on a road, and you come to a fork in the road. You know that one path leads to a pot of gold and the other path leads to a dragon. There are two elves at the fork, both of whom know the way
to the pot of gold. You know that one elf always tells the truth and the other elf always lies, but you don’t know which elf is which. What single question should you ask to figure out the proper path to the pot
of gold?
import java.util.Scanner;
public class BowlingScores
{
}
// end BowlingScores class
public static void main(String[] args)
{
}
// end main
Scanner stdIn = new Scanner(System.in);
int score;
int totalScore = 0;
int count = 0;
double average;
System.out.print("Enter score (-1 to quit): ");
score = stdIn.nextInt();
while (score >= 0)
{
}
totalScore += score;
count++;
System.out.print("Enter score (-1 to quit): ");
score = stdIn.nextInt();
average = (double) totalScore / count;
Apago PDF Enhancer
System.out.println("Average score is " + average);
x = stdIn.nextInt();
System.out.println("square = " + (x * x));
while (x != 0);