JAVA: An Introduction to Problem Solving & Programming, 7th Ed. By Walter Savitch.
ISBN 0133862119
© 2015 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

 

   

Listing 4.1


import java.util.Scanner;
public class WhileDemo
{
    public static void main (String [] args)
    {
        int count, number;
        System.out.println ("Enter a number");
        Scanner keyboard = new Scanner (System.in);
        number = keyboard.nextInt ();
        count = 1;
        while (count <= number)
        {
            System.out.print (count + ", ");
            count++;
        }
        System.out.println ();
        System.out.println ("Buckle my shoe.");
    }
}

 

 

Listing 4.2


import java.util.Scanner;
public class DoWhileDemo
{
    public static void main (String [] args)
    {
        int count, number;
        System.out.println ("Enter a number");
        Scanner keyboard = new Scanner (System.in);
        number = keyboard.nextInt ();
        count = 1;
        do
        {
            System.out.print (count + ", ");
            count++;
        }
        while (count <= number);
        System.out.println ();
        System.out.println ("Buckle my shoe.");
    }
}

 

 

 

Algorithm for Roach Population Program


Algorithm for roach population program
1. Read houseVolume
2. Read startPopulation
3. population = startPopulation
4. totalBugVolume = population * ONE_BUG_VOLUME
5. countWeeks = 0
6. while (totalBugVolume < houseVolume)
{
    newBugs = population * GROWTH_RATE
    newBugVolume = newBugs * ONE_BUG_VOLUME
    population = population + newBugs
    totalBugVolume = totalBugVolume + newBugVolume
    countWeeks = countWeeks + 1
}
7. Display startPopulation, houseVolume, countWeeks, population, and totalBugVolume

 

 

 

Listing 4.3


import java.util.Scanner;
/**
Program to calculate how long it will take a population of
roaches to completely fill a house from floor to ceiling.
*/
public class BugTrouble
{
    public static final double GROWTH_RATE = 0.95; //95% per week
    public static final double ONE_BUG_VOLUME = 0.002; //cubic feet
    public static void main (String [] args)
    {
        System.out.println ("Enter the total volume of your house");
        System.out.print ("in cubic feet: ");
        Scanner keyboard = new Scanner (System.in);
        double houseVolume = keyboard.nextDouble ();
        System.out.println ("Enter the estimated number of");
        System.out.print ("roaches in your house: ");
        int startPopulation = keyboard.nextInt ();
        int countWeeks = 0;
        double population = startPopulation;
        double totalBugVolume = population * ONE_BUG_VOLUME;
        double newBugs, newBugVolume;
        while (totalBugVolume < houseVolume)
        {
            newBugs = population * GROWTH_RATE;
            newBugVolume = newBugs * ONE_BUG_VOLUME;
            population = population + newBugs;
            totalBugVolume = totalBugVolume + newBugVolume;
            countWeeks++;
        }
        System.out.println ("Starting with a roach population of " +
                startPopulation);
        System.out.println ("and a house with a volume of " + houseVolume +
                " cubic feet,");
        System.out.println ("after " + countWeeks + " weeks,");
        System.out.println ("the house will be filled with " +
                (int) population + " roaches.");
        System.out.println ("They will fill a volume of " +
                (int) totalBugVolume + " cubic feet.");
        System.out.println ("Better call Debugging Experts Inc.");
    }
}

 

 

 

Listing 4.4


import java.util.Scanner;
/**
Computes the average of a list of (nonnegative) exam scores.
Repeats computation for more exams until the user says to stop.
*/
public class ExamAverager
{
    public static void main (String [] args)
    {
        System.out.println ("This program computes the average of");
        System.out.println ("a list of (nonnegative) exam scores.");
        double sum;
        int numberOfStudents;
        double next;
        String answer;
        Scanner keyboard = new Scanner (System.in);
        do
        {
            System.out.println ();
            System.out.println ("Enter all the scores to be averaged.");
            System.out.println ("Enter a negative number after");
            System.out.println ("you have entered all the scores.");
            sum = 0;
            numberOfStudents = 0;
            next = keyboard.nextDouble ();
            while (next >= 0)
            {
                sum = sum + next;
                numberOfStudents++;
                next = keyboard.nextDouble ();
            }
            if (numberOfStudents > 0)
                System.out.println ("The average is " +
                        (sum / numberOfStudents));
            else
                System.out.println ("No scores to average.");
            System.out.println ("Want to average another exam?");
            System.out.println ("Enter yes or no.");
            answer = keyboard.next ();
        }
        while (answer.equalsIgnoreCase ("yes"));
    }
}

 

 

 

Listing 4.5


public class ForDemo
{
    public static void main (String [] args)
    {
        int countDown;
        for (countDown = 3 ; countDown >= 0 ; countDown--)
        {
            System.out.println (countDown);
            System.out.println ("and counting.");
        }
        System.out.println ("Blast off!");
    }
}

 

 

 

Listing 4.6


import java.util.Scanner;
/**
Illustrates the use of a boolean variable to end loop iteration.
*/
public class BooleanDemo
{
    public static void main (String [] args)
    {
        System.out.println ("Enter nonnegative numbers.");
        System.out.println ("Place a negative number at the end");
        System.out.println ("to serve as an end marker.");
        int sum = 0;
        boolean areMore = true;
        Scanner keyboard = new Scanner (System.in);
        while (areMore)
        {
            int next = keyboard.nextInt ();
            if (next < 0)
                areMore = false;
            else
                sum = sum + next;
        }
        System.out.println ("The sum of the numbers is " + sum);
    }
}

 

 

 

Spending Spree Algorithm


    1. amountRemaining = amount of gift certificate
    2. totalSpent = 0
    3. itemNumber = 1
    4. while (we have money left to spend and (itemNumber <= max number of items))
    {
    Display amount of money left and number of items that can be bought.
        Read cost of proposed purchase.
        if (we can afford the purchase)
        {
            Display a message.
            totalSpent = totalSpent + cost of item
            Update amountRemaining
            if (amountRemaining > 0)
            {
                Display amount of money left.
                itemNumber++
            }
            else
            {
                Display a message (no more money).
                Make this the last loop iteration.
            }
        }

        else
        Display a message (item is too expensive).
        }

        Display amount of money spent and farewell message.
      

 

 

Listing 4.7


import java.util.Scanner;
public class SpendingSpree
{
    public static final int SPENDING_MONEY = 100;
    public static final int MAX_ITEMS = 3;
    public static void main (String [] args)
    {
        Scanner keyboard = new Scanner (System.in);
        boolean haveMoney = true;
        int leftToSpend = SPENDING_MONEY;
        int totalSpent = 0;
        int itemNumber = 1;
        while (haveMoney && (itemNumber <= MAX_ITEMS))
        {
            System.out.println ("You may buy up to " +
                    (MAX_ITEMS - itemNumber + 1) +
                    " items");
            System.out.println ("costing no more than $" +
                    leftToSpend + ".");
            System.out.print ("Enter cost of item #" +
                    itemNumber + ": $");
            int itemCost = keyboard.nextInt ();
            if (itemCost <= leftToSpend)
            {
                System.out.println ("You may buy this item. ");
                totalSpent = totalSpent + itemCost;
                System.out.println ("You spent $ + totalSpent +
                        so far. ");
                        leftToSpend = SPENDING_MONEY - totalSpent;
                if (leftToSpend > 0)
                    itemNumber++;
                else
                {
                    System.out.println ("You are out of money.);
                            haveMoney = false;
                }
            }
            else
                System.out.println ("You cannot buy that item.");
        }
        System.out.println ("You spent $" + totalSpent +
                ", and are done shopping.");
    }
}

 

 

 

Listing 4.9


import javax.swing.JApplet;
import java.awt.Graphics;
import java.awt.Color;
public class MultipleFaces extends JApplet
{
    public static final int FACE_DIAMETER = 50;
    public static final int X_FACE0 = 10;
    public static final int Y_FACE0 = 5;
    public static final int EYE_WIDTH = 5;
    public static final int EYE_HEIGHT = 10;
    public static final int X_RIGHT_EYE0 = 20;
    public static final int Y_RIGHT_EYE0 = 15;
    public static final int X_LEFT_EYE0 = 45;
    public static final int Y_LEFT_EYE0 = Y_RIGHT_EYE0;
    public static final int NOSE_DIAMETER = 5;
    public static final int X_NOSE0 = 32;
    public static final int Y_NOSE0 = 25;
    public static final int MOUTH_WIDTH = 30;
    public static final int MOUTH_HEIGHT0 = 0;
    public static final int X_MOUTH0 = 20;
    public static final int Y_MOUTH0 = 35;
    public static final int MOUTH_START_ANGLE = 180;
    public static final int MOUTH_EXTENT_ANGLE = 180;
    public void paint (Graphics canvas)
    {
        super.paint(canvas);
        int i, xOffset, yOffset; //Want i to exist after the loop ends
        for (i = 0 ; i <= 4 ; i++)
        { //Draw one face:
            xOffset = 50 * i;
            yOffset = 30 * i;
            //Draw face interior and outline:
            if (i % 2 == 0) //if i is even,
            { //Make face yellow
                canvas.setColor (Color.YELLOW);
                canvas.fillOval (X_FACE0 + xOffset, Y_FACE0 + yOffset,
                        FACE_DIAMETER, FACE_DIAMETER);
            }
            canvas.setColor (Color.BLACK);
            canvas.drawOval (X_FACE0 + xOffset, Y_FACE0 + yOffset,
                    FACE_DIAMETER, FACE_DIAMETER);
            //Draw eyes:
            canvas.setColor (Color.BLUE);
            canvas.fillOval (X_RIGHT_EYE0 + xOffset, Y_RIGHT_EYE0 + yOffset,
                    EYE_WIDTH, EYE_HEIGHT);
            canvas.fillOval (X_LEFT_EYE0 + xOffset, Y_LEFT_EYE0 + yOffset,
                    EYE_WIDTH, EYE_HEIGHT);
            //Draw nose:
            canvas.setColor (Color.BLACK);
            canvas.fillOval (X_NOSE0 + xOffset, Y_NOSE0 + yOffset,
                    NOSE_DIAMETER, NOSE_DIAMETER);
            //Draw mouth:
            canvas.setColor (Color.RED);
            canvas.drawArc (X_MOUTH0 + xOffset, Y_MOUTH0 + yOffset,
                    MOUTH_WIDTH, MOUTH_HEIGHT0 + 3 * i,
                    MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE);
        }
        //i is 5 when the previous loop ends
        xOffset = 50 * i;
        yOffset = 30 * i;
        //Draw kissing face:
        //Draw face outline:
        canvas.setColor (Color.BLACK);
        canvas.drawOval (X_FACE0 + xOffset, Y_FACE0 + yOffset,
                FACE_DIAMETER, FACE_DIAMETER);
        //Draw eyes:
        canvas.setColor (Color.BLUE);
        canvas.fillOval (X_RIGHT_EYE0 + xOffset, Y_RIGHT_EYE0 + yOffset,
                EYE_WIDTH, EYE_HEIGHT);
        canvas.fillOval (X_LEFT_EYE0 + xOffset, Y_LEFT_EYE0 + yOffset,
                EYE_WIDTH, EYE_HEIGHT);
        //Draw nose:
        canvas.setColor (Color.BLACK);
        canvas.fillOval (X_NOSE0 + xOffset, Y_NOSE0 + yOffset,
                NOSE_DIAMETER, NOSE_DIAMETER);
        //Draw mouth in shape of a kiss:
        canvas.setColor (Color.RED);
        canvas.fillOval (X_MOUTH0 + xOffset + 10, Y_MOUTH0 + yOffset,
                MOUTH_WIDTH - 20, MOUTH_WIDTH - 20);
        //Add text:
        canvas.drawString ("Kiss, Kiss.",
                X_FACE0 + xOffset + FACE_DIAMETER, Y_FACE0 + yOffset);
        //Draw blushing face:
        i++;
        xOffset = 50 * i;
        yOffset = 30 * i;
        //Draw face interior and outline:
        canvas.setColor (Color.PINK);
        canvas.fillOval (X_FACE0 + xOffset, Y_FACE0 + yOffset,
                FACE_DIAMETER, FACE_DIAMETER);
        canvas.setColor (Color.BLACK);
        canvas.drawOval (X_FACE0 + xOffset, Y_FACE0 + yOffset,
                FACE_DIAMETER, FACE_DIAMETER);
        //Draw eyes:
        canvas.setColor (Color.BLUE);
        canvas.fillOval (X_RIGHT_EYE0 + xOffset, Y_RIGHT_EYE0 + yOffset,
                EYE_WIDTH, EYE_HEIGHT);
        canvas.fillOval (X_LEFT_EYE0 + xOffset, Y_LEFT_EYE0 + yOffset,
                EYE_WIDTH, EYE_HEIGHT);
        //Draw nose:
        canvas.setColor (Color.BLACK);
        canvas.fillOval (X_NOSE0 + xOffset, Y_NOSE0 + yOffset,
                NOSE_DIAMETER, NOSE_DIAMETER);
        //Draw mouth: (same as on face before kissing one)
        canvas.setColor (Color.RED);
        canvas.drawArc (X_MOUTH0 + xOffset, Y_MOUTH0 + yOffset,
                MOUTH_WIDTH, MOUTH_HEIGHT0 + 3 * (i - 2),
                MOUTH_START_ANGLE, MOUTH_EXTENT_ANGLE);
        //Add text:
        canvas.drawString ("Tee Hee.",
                X_FACE0 + 50 * i + FACE_DIAMETER, Y_FACE0 + yOffset);
    }
}