Java: Java Problem Solving and Programming - CH 4 Exercises Flashcards


Set Details Share
created 13 years ago by primet21
18,635 views
book cover
Java
Chapter 4
Chapter 3 - Flow of Control: Loops
updated 11 years ago by primet21
Grade levels:
9th grade, 10th grade, 11th grade, 12th grade, College: First year, College: Second year, College: Third year, College: Fourth year, Graduate school, Professional
Subjects:
programming, java, computers, beginner, programming languages
show moreless
Page to share:
Embed this setcancel
COPY
code changes based on your size selection
Size:
X
Show:

1

Write a fragment of code that will read words from the keyboard until the word done is entered. For each word except done, report whether its first character is equal to its last character. For the required loop, use a
a)while statement
b)do-while statement

a)
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word");
String word = keyboard.next();
while(!word.equals("done"))
{
if(word.charAt(0) == word.charAt(word.length() - 1))
{
System.out.println("First and last character are equals for the word: " + word);
}
else
{
System.out.println("First and last character are NOT equals for the word: " + word);
}
word = keyboard.next();
}

b)
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a word");
String word = keyboard.next();
do
{
if(word.charAt(0) == word.charAt(word.length() - 1))
{
System.out.println("First and last character are equals for the word: " + word);
}
else
{
System.out.println("First and last character are NOT equals for the word: " + word);
}
word = keyboard.next();
}while(!word.equals("done"));

2

Develop an algorithm for computing the month-by-month balance in your savings account. You can make one transaction-a deposit or a withdrawal-each month. Interest is added to the account at the beginning of each month. The monthly interest rate is the yearly percentage rate divided by 12.

double balance = 0.0,
yearlyRate = 0.025;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter d for deposit, w for withdrawal or x to exit");
String transaction = keyboard.next();
while(!transaction.equals("x"))
{
if(balance > 0.0)
{
balance += (yearlyRate / 12) * balance;
}
System.out.println("Beginning of Month Balance: " + balance);
if(transaction.equals("d"))
{
System.out.println("Enter deposit amount");
balance += keyboard.nextDouble();
}
else if(transaction.equals("w"))
{
System.out.println("Enter withdrawal amount");
balance -= keyboard.nextDouble();
}
System.out.println("Balance after transaction: " + balance);
System.out.println("Enter d for deposit, w for withdrawal or x to exit");
transaction = keyboard.next();
}

3

Develop an algorithm for a simple game of guessing at a secret five-digit code. When the user enters a guess at the code, the program returns two values: the number of digits in the guess that are in the correct position and the sum of those digits. For example, if the secret code is 53840, and the user guesses 83241, the digits 3 and 4 are in the correct position. Thus, the program should respond with 2 and 7. Allow the user to guess a fixed number of times.

String code = "37823";
int totalGuesses = 1;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your 5-digit guess");
String guess = keyboard.next();
while(totalGuesses < 10)
{
int correct = 0,
sum = 0;
for(int i = 0; i < code.length(); i++)
{
if(code.charAt(i) == guess.charAt(i))
{
correct++;
sum += Integer.parseInt(code.charAt(i) + "");
}
}
System.out.println(correct + " and " + sum);
if(guess.equals(code))
{
System.out.println("You guessed right!");
totalGuesses = 10;
}
else
{
guess = keyboard.next();
totalGuesses++;
}
}

4

Write a fragment of code that will compute the sum of the first n positive odd integers. For example, if n is 5, you should compute 1 + 3 + 5 + 7 + 9.

int n = 5,
number = 1,
sum = 0;
for(int i = 0; i < n; i++)
{
sum += number;
number += 2;
}
System.out.println("Sum of 1st " + n + " positive odd ints is: " + sum);

5

Convert the following code so that it uses nested while statements instead of for statements:
int s = 0;
int t = 1;
for (int i = 0; i < 10; i++)
{
s = s + i;
for (int j = i; j > 0; j−−)
{
t = t * (j - i);
}
s = s * t;
System.out.println("T is " + t);
}
System.out.println("S is " + s);

int s = 0;
int t = 1;
int i = 0;
while(i < 10)
{
s = s + i;
int j = i;
while(j > 0)
{
t = t * (j - i);
j--;
}
s = s * t;
System.out.println("T is " + t);
i++;
}
System.out.println("S is " + s);

6

Write a for statement to compute the sum 1 + 2² + 3² + 4² + 5² + ... + n².

int n = 20,
sum = 0;
for(int i = 1; i <= n; i++)
{
sum += (i * i);
}
System.out.println("Total sum: " + sum);

7

(Optional) Repeat the previous question, but use the comma operator and omit the for statement’s body.

int n = 20,
sum,
i;
for(i = 1, sum = 0; i < n; sum += i * i, i++);
System.out.println("Total sum: " + sum);

8

Write a loop that will count the number of blank characters in a given string.

String word = "hello w o r l d";
int blankSpaces = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == ' ')
{
blankSpaces++;
}
}
System.out.println(blankSpaces + " blank spaces in " + word);

9

Write a loop that will create a new string that is the reverse of a given string.

String word = "0123456789",
reversed = "";
for(int i = word.length() - 1; i > -1; i--)
{
reversed += word.charAt(i);
}
System.out.println(word + " reversed is " + reversed);

10

Write a program that will compute statistics for eight coin tosses. The user will enter either an h for heads or a t for tails for the eight tosses. The program will then display the total number and percentages of heads and tails. Use the increment operator to count each h and t that is entered. For example, a possible sample dialogue between the program and the user might be

For each coin toss enter either h for heads or t for tails.
First toss: h
Second toss: t
Third toss: t
Fourth toss: h
Fifth toss: t
Sixth toss: h
Seventh toss: t
Eighth toss: t
Number of heads: 3
Number of tails: 5
Percent heads: 37.5
Percent tails: 62.5

Scanner keyboard = new Scanner(System.in);
int heads = 0,
tails = 0;
System.out.println("For each coin toss enter either h for heads or t for tails.");
for(int i = 1; i <= 8; i++)
{
String numEnding = "th";
if(i == 1)
{
numEnding = "st";
}
else if(i == 2)
{
numEnding = "nd";
}
else if(i == 3)
{
numEnding = "rd";
}
System.out.println(i + numEnding + " toss:");
String type = keyboard.next();
if(type.equals("h"))
{
heads++;
}
else
{
tails++;
}
}
System.out.println("Number of heads: " + heads + " (" + (((double)heads / 8.0) * 100) + "%)");
System.out.println("Number of tails: " + tails + " (" + (((double)tails / 8.0) * 100) + "%)");

11

Suppose we attend a party. To be sociable, we will shake hands with everyone else. Write a fragment of code using a for statement that will compute the total number of handshakes that occur. (Hint: Upon arrival, each person shakes hands with everyone that is already there. Use the loop to find the total number of handshakes as each person arrives.)

int numOfPeople = 5,
totalHandshakes = 0;
for(int i = 0; i < numOfPeople; i++)
{
totalHandshakes += i;
}
System.out.println("Total handshakes for " + numOfPeople + " is " + totalHandshakes);

12

Define an enumeration for each of the months in the year. Use a for-each statement to display each month.

enum Month
{
January, February, March, April,
May, June, July, August,
September, October, November, December
}
public static void main(String[] args)
{
for(Month m : Month.values())
{
System.out.println(m);
}
}

13

Write a fragment of code that computes the final score of a baseball game. Use a loop to read the number of runs scored by both teams during each of nine innings. Display the final score afterwards.

Scanner keyboard = new Scanner(System.in);
int visitorScore = 0,
homeScore = 0,
inning = 1;
while(inning <= 9)
{
System.out.println("Enter runs scored by visiting team in inning " + inning);
visitorScore += keyboard.nextInt();
System.out.println("Enter runs scored by home team in inning " + inning);
homeScore += keyboard.nextInt();
inning++;
}
System.out.println("Final: Visitors - " + visitorScore + " Home - " + homeScore);

14

Suppose that you work for a beverage company. The company wants to know the optimal cost for a cylindrical container that holds a specified volume. Write a fragment of code that uses an ask-before-iterating loop. During each iteration of the loop, your code will ask the user to enter the volume and the radius of the cylinder. Compute and display the height and cost of the container. Use the following formulas, where V is the volume, r is the radius, h is the height, and C is the cost.

h = V/πr²
C = 2πr(r + h)

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter cylinder volume or -1 to exit:");
double v = keyboard.nextDouble();
double r = 0.0;
if(v > 0.0)
{
System.out.println("Enter cylinder radius:");
r = keyboard.nextDouble();
}
while(v > 0.0)
{
double h = v / (Math.PI * (r * r));
double c = 2 * Math.PI * r * (r + h);
System.out.println("Height: " + h + "\nCost: " + c);
System.out.println("Enter cylinder volume or -1 to exit:");
v = keyboard.nextDouble();
if(v > 0.0)
{
System.out.println("Enter cylinder radius:");
r = keyboard.nextDouble();
}
}

15

Suppose that we want to compute the geometric mean of a list of positive values. To compute the geometric mean of k values, multiply them all together and then compute the kth root of the value. For example, the geometric mean of 2, 5, and 7 is ³√2x5x7. Use a loop with a sentinel value to allow a user to enter an arbitrary number of values. Compute and display the geometric mean of all the values, excluding the sentinel. (Hint: Math.pow(x, 1.0/k) will compute the kth root of x.)

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter positive values to compute the geometric mean for");
System.out.println("Enter 0 after you have entered all values");
int value = keyboard.nextInt(),
count = 0,
product = 1;
while(value > 0)
{
product = product * value;
count++;
value = keyboard.nextInt();
}
double geometricMean = Math.pow(product, 1.0 / count);
System.out.println("The geometric mean is: " + geometricMean);

16

Image a program that compresses files by 80 percent and stores them on storage media. Before the compressed file is stored, it must be divided into blocks of 512 bytes each. Develop an algorithm for this program that first reads the number of blocks available on the storage media. Then, in a loop, read the uncompressed size of a file and determine whether the compressed file will fit in the space left on the storage media. If so, the program should compress and save the file. It continues until it encounters a file that will exceed the available space on the media.

For example, suppose the media can hold 1000 blocks. A file of size 1100 bytes will compress to size 880 and require 2 blocks. The available space is now 998 blocks. A file of size 20,000 bytes will compress to size 16,000 and require 32 blocks. The available space is now 966.

Read the number of block available and store in blocks
Read the size of the first file and store in fileSize
Multiply fileSize by 0.8
Divide fileSize by 512 (round up) and store in blocksNeeded
Subtract blocksNeeded from blocks
WHILE blocks > 0
Read the size of the next file and store in fileSize
Multiply fileSize by 0.8
Divide fileSize by 512 (round up) and store in blocksNeeded
Subtract blocksNeeded from blocks
END WHILE
Display "Store Media is Full!"

17

Create an applet that draws a pattern of circles whose centers are evenly spaced along a horizontal line. Use six constants to control the pattern: the number of circles to draw, the diameter of the first circle, the x- and y- coordinates of the center of the first circle, the distance between adjacent centers, and the change in the diameter of each subsequent circle.

import java.applet.*;
import java.awt.*;

public class A extends Applet
{
private final int NUM_OF_CIRCLES = 10,
FIRST_CIRCLE_DIAMETER = 20,
FIRST_CIRCLE_X = 40,
FIRST_CIRCLE_Y = 150,
DISTANCE_BETWEEN = 40,
DIAMETER_CHANGE = 10;

public void paint(Graphics g)
{
int d = FIRST_CIRCLE_DIAMETER;
int x = FIRST_CIRCLE_X;
for(int i = 0; i < NUM_OF_CIRCLES; i++)
{
g.drawOval(x - (d / 2), FIRST_CIRCLE_Y - (d / 2), d, d);
x += DISTANCE_BETWEEN;
d += DIAMETER_CHANGE;
}
}
}

18

What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?
int product = 1;
int max = 20;
for (int i = 0; i <= max; i++)
product = product * i;
System.out.println("The product is " + product);

Display:
The product is 0

Programmers Intent:
The programmer wanted to get the product of numbers 1 - 20. However, since i begins as 0, and anything multiplied by 0 is always 0 then the result will be 0.

To Fix:
Change int i = 0 to int i = 1. You will also have to change product to long since the result is too large to store in an int.

19

What does the following fragment of code display? What do you think the programmer intended the code to do, and how would you fix it?
int sum = 0;
int product = 1;
int max = 20;
for (int i = 1; i <= max; i++)
sum = sum + i;
product = product * i;
System.out.println("The sum is " + sum + " and the product is " + product);

Display:
Does not compile because variable i is limited to the scope of the for statement which does not include product = product * i.

Programmers Intent:
The programmer wanted to get the product and sum of numbers 1 - 20. However, brackets are needed when a for statement has more than 1 statement.

To Fix:
for (int i = 1; i <= max; i++)
{
sum = sum + i;
product = product * i;
}

Just like question #18 you will also have to change product to long since the result is too large to store in an int.