Spring Semester 2004


Homework Assignment Four: Practical Exam Review

Due date
Thursday March 25, 11:59pm
Late policy
Try to turn everything on time, no solutions will be accepted late.

Work policy
Working in groups is encouraged but please turn in your own version of the assignment.

Also, please make sure you

the Computer Science Department's Statement on Academic Integrity before turning in your assignment.

Task
You need to review the core elements of the problems from Homework Three and Past.

  1. Write code to find the greatest common divisor of two numbers.

    The two numbers are integers and strictly positive. One of them is smaller. (What if they're equal?) Then the divisor being common can't but divide them both and be smaller or equal than both. So now you have two ways of approaching this: you either start testing numbers from the smaller of the two down, and the first one that divides both numbers is the greatest common divisor(could be 1), or start from 1 (which divides them both evenly) and keep going up (but not above the smaller of the two numbers) and as soon as you find a new common divisor keep it as the greatest common divisor thus far, discarding what previous greatest common divisor thus far on the occasion. This second approach is a bit more laborious (the bookkeeping is more involved) as discussed in class yesterday.

  2. Write code to find if a number is prime or not.

    A prime number is a number that doesn't have any divisors except 1 and the number itself. For example 13. 12 is not a prime number. So if you were to check the numbers from 2 to the number we're investigating (minus one), one by one, you would say that the number is prime if none of the numbers between 2 and the number minus one evenly divides the number in question. Otherwise the number is not prime. There are several ways in which you could optimize this but I think you should use a for loop from 2 to n-1 and check the numbers (i) one by one to see if they evenly divide the number (remainder of the division betwen n and i should be 0 where n is the number). The moment you find a divisor you have the answer: the number is not prime. If no divisor is found you also have the answer: the number is prime. This procedure is similar to contains for arrays as discussed before the break.

  3. Write code to list the prime factors of a number.

    The prime factors of a number are those prime numbers smaller than the number, divisors of the number. More to come later, but for now I think you can get started.

    Here's an idea, at the very least explain how this goes:

    class Wizard {
        int countFactors(int number) {
    	int count = 0; 
            for (int i = 2; number > 1; i++) {
    	    while (number % i == 0 ) {
    		count += 1; 
                    System.out.println(i);
    		number = number / i;
    	    }
    	}
    	return count; 
        } 
    
    
        public static void main(String[] args) {
          Wizard a = new Wizard(); 
          a.countFactors(Integer.parseInt(args[0])); 
        }
    }
  4. Write code to produce random numbers in a certain range

    This has been discussed in class several times: Lab Eight and several lecture notes.

    I will reproduce those explanations here as soon as I get the rest done.

  5. Write code to calculate square roots like the Babylonians.

    This is described at length in the "sOAKed" notes.

    I also went over it in class yesterday.

    The key is that we start from a guess (any guess) and keep improving it.

    At any point in time we need to be able to determine if the guess is good enough or not.

    Here's a solution please try to explain this at least:

    frilled.cs.indiana.edu%cat RootApproximator.java
    class RootApproximator {
        double n; 
        double currentGuess; 
        RootApproximator(double number) {
    	n = number; 
            currentGuess = 1; 
        }
        public boolean hasMoreGuesses() {
            return Math.abs(n - currentGuess * currentGuess) > 0.00000000001; 
        }
        public double nextGuess() {
            currentGuess = (currentGuess + n / currentGuess) / 2; 
            return currentGuess; 
        }
        public static void main(String[] args) {
            RootApproximator r = new RootApproximator(5);
    	while (r.hasMoreGuesses())
    	    System.out.println(r.nextGuess());
        }
    }
    frilled.cs.indiana.edu%javac RootApproximator.java
    frilled.cs.indiana.edu%java RootApproximator
    3.0
    2.3333333333333335
    2.238095238095238
    2.2360688956433634
    2.236067977499978
    frilled.cs.indiana.edu%
  6. Write code that calculates the sum of the squares of the digits of a positive integer (represented as a String).

    This is what Tigger was doing. The key here is to be able to extract the characters one by one.

    You can use charAt() and then you end up with characters. To get numbers out of those you'd have to do something like this: '9' - '0', '3' - '0', to obtain 9 or 3 (the numbers) since characters are nothing but codes that can be shown as shapes. The alternative would be to extract individual characters as substrings and then parse them into the numbers they represent:

    Integer.parseInt(a.substring(4,4))
    would do that for the character that is in the fifth position of the String that is pointed to by the variable with the name a.

    Here's a digit extractor, perhaps it will get you started?

    class DigitExtractor {
      int theNumber; 
      int index;  
      String theCopy;
      DigitExtractor (int aNumber) { 
        this.theNumber = aNumber; 
        this.theCopy = this.theNumber + ""; 
        this.index = this.theCopy.length();
      }
      int nextDigit() {
        this.index -= 1; 
        return theCopy.charAt(this.index) - '0'; 
      }
      boolean hasMoreDigits() {
        if (index > 0) return true;
        else return false; 
      }
    
      public static void main(String[] args) {
        DigitExtractor d = new DigitExtractor(123456789); 
        while (d.hasMoreDigits()) {
          System.out.println(d.nextDigit()); 
        }
      }
    }

  7. Write code that finds the largest number in a sequence of numbers (tokens in a line (String) entered by user).

    The user types a series of numbers on a line. The numbers are separated by spaces. To get them out (as tokens) you need to use a string tokenizer. Once you get the tokens (one by one) you need to use them. They're Strings and you need to turn them into numbers (assume we work with ints). Parsing is the way to go here. How do you find the largest of the numbers? Apply the strategy we used with finding the greatest common divisor: if the line does not contain any numbers that's an error. The first number is the largest thus far. You need to look at all the numbers. Each time you find a bigger number you need to update your knowledge of the largest number that you've seen thus far.

  8. Same as above except calculate the average and the standard deviation:
    The average of the numbers (also known as the data set)
    has the following (well-known) formula:

    We worked this out on Tuesday we will look at it again on Thursday.

    First calculate the sum of all elements. Divide that by how many you have to obtain the average. Then start calculating the individual deviations to the mean. What you really want to do is to be able to calculate the sum of the squares of the squared deviations. If you then divide that by how many numbers you have (minus one) you obtain the square of the standard deviation. Taking the square root of that would give you the standard deviation.

  9. Same above except use this formula for the standard deviation:

    Remember that there are three of you: the executive that knows what (s)he wants and has an idea of why that is possible, the analyst that doesn't question the purpose but finds the solution and knows something about the coding but doesn't do any coding per se, and the programmer who receives the solution formulated by the analyst and does not care much about improving the solution, but understand where the analyst is coming from. The programmer basically only does coding. The executive talks to the analyst. The analyst to the programmer. The programmer shows the program to the executive directly. The executive says "I like it" or "You're fired." and you are all these three people. Or the same person wearing all three hats. Keep this in mind when you solve this problem, and any problem in fact.

    So for this problem you need to calculate two kinds of sums as you go through the numbers: one is the sum of the squares of the numbers (s1) and the other one is the squared sum of the numbers (s2). Once you have that you just use the two (and n) to calculate the formula. To calculate the sums you need to loop through all the numbers and do something with each of them as you're building the corresponding sums.

    Here's a solution. At the very least explain it:

    class StdDev {
        public static void main(String[] args) {
    	ConsoleReader console = new ConsoleReader(System.in); 
    	while (true) {
    	    System.out.print("Numbers> "); 
    	    String line = console.readLine();
    	    if (line.equals("")) break; 
    	    StringTokenizer stapler = new StringTokenizer(line); 
    	    double sum = 0; 
    	    double squares = 0; 
    	    int count = 0; 
    	    while (stapler.hasMoreTokens()) {
    		int number = Integer.parseInt(stapler.nextToken()); 
    		sum += number;
    		squares += number * number; 
    		count += 1; 
    	    }
    	    System.out.println(count + 
    			       (count > 1 ? " numbers" : " number") + 
    			       ", average is: " 
    			       + sum / count);
    
    	    System.out.println("Standard deviation is: " +
    			       Math.sqrt((squares - sum * sum / count) 
    					 / (count - 1))
    			       ); 
    	}
        }
    }
  10. Write code that plays guess the number in ten tries with the user There's a loop in here that reads and checks and counts.

    It ends when you're out of attempts or when you guess.

    This is just like the Babylonian method for calculating the square roots.

    Except successive guesses are not ours, they just come from the user.

    Here's a solution. At the very least please explain it:

    class Guess {
        public static void main(String[] args) {
    	ConsoleReader console = new ConsoleReader(System.in); 
    	System.out.println("Hello, and welcome to the Guessing Game."); 
    	int number = (int)(Math.random() * 100); 
    	int count = 0; 
    	while (count < 10) {
    	    count += 1; 
    	    System.out.print("(" + number + ")Guess[" + count + "]: "); 
    	    int guess = console.readInt(); 
    	    if (guess == number) {
    		System.out.println("You won! Congratulations."); 
    		break; 
    	    } else {
    		if (guess < number) 
    		    System.out.println("Too low. Please try higher.");
    		else System.out.println("Too high. Please try lower."); 
    	    }
    	}
            if (count == 10) 
    	    System.out.println("You lost. Better luck next time.");
        }
    }
  11. Describe the organization and functionality of the following classes from past assignments:
    Point (from Homework Two)
    Line (from Homework Two)
    Triangle (from Homework Two)
    Drunkard (from Homework Three)
    Tigger (from Homework Three)
    Elevator (from Homework Two)
    BubbleMachine (from Homework Two)
    Athlete (from Homework Two)
    BankAccount (from Homework Two)
    Fraction (from Lecture Notes Fifteen)
    BasketballPlayer (from the Pacers problem)
    PileOfMarbles (from the Game of Nim)
    Runner (from Homework Three)
    Student (from Lab Four)
    Car (from Lab Four)
    BeerCan (from Lab Four)
    Your description must cover the following aspects:
    a) instance variables used
    b) instance methods used
    c) constructors and their role
    e) basic test program(s) for these classes

    The classes are provided below just to make sure you don't have to scramble to create them.

    So here they are:

    
    class Point {
      double x;
      double y;
      Point(double a, double b) {
        ... 
      }
      double dist(Point other) {
        ... 
      }
    }
    
    class Triangle {
      Point a, b, c;
      Triangle (double x1, double y1,
                double x2, double y2,
                double x3, double y3) {
        ... 
      }
      double area() {
        ... 
      }
    }
    
    class Experiment {
      public static void main(String[] args) {
        Triangle a = new Triangle(0, 0, 0, 3, 4, 0);
        System.out.println(a.area());  // prints 3 * 4 / 2 (that is: 6 (six))
        System.out.println((new Point(0, 3)).dist(new Point(4, 0))); // (5.0)
      }
    }
    
    //----------------------------------------------------------------------
    
    class Elevator {
        int floor; 
        Elevator(int floor) {
            ...
        }  
        void up(int to) {
            ... 
        }
        void down(int to) {
            ...
        }
        void report() {
            ...
        }
        int currentFloor() { 
            ... 
        } 
        public static void main(String[] args) {
    	Elevator e = new Elevator(20); 
    	e.up(26); 
    	e.down(14); 
            e.up(10); 
    	e.down(30); 
            e.up(e.currentFloor() + 3); 
        }
    }
    
    //----------------------------------------------------------------------
    
    class One {
        public static void main(String[] args) {
    	Line a = new Line(new Point(0, 0), new Point (1, 1)); 
    	System.out.println(a.length()); 
        }
    }
    
    class Line {
        Point a, b; 
        Line(Point a, Point b) {
          ... 
        }
        double length() {
          ... 
        }
    }
    
    class Point {
        double x, y;
        Point(double x, double y) {
          ... 
        }
        double distanceTo(Point other) {
          ... 
        }
    }
    
    //----------------------------------------------------------------------
    
    class Tigger {
        String x, y; 
        Tigger(int x, int y) {
          ... 
        }
        void bounce() {
          int a = calculate(x), 
              b = calculate(y); 
          this.x = a + "";
          this.y = b + ""; 
    
        }
        int calculate(String a) {
          int sum = 0; 
          ... 
          return sum; 
        }
        String report() {
          ... 
        }
    } 
    
    //----------------------------------------------------------------------
    
    class Fraction {
        private int numerator;
        private int denominator;
        public Fraction(int num, int den) {
          ... 
        }
        public String toString() {
          ... 
        }
        public boolean isZero() {
          ... 
        }
        public boolean isInt() {
          ... 
        }
        public boolean equals(Fraction other) {
          ... 
        }
        public boolean greaterThan(Fraction other) {
          ... 
        }
        public Fraction minus(Fraction other) {
          ... 
        }
        public Fraction plus(Fraction other) {
          ... 
        }
        public Fraction times(Fraction other) {
          ... 
        }
        public Fraction divideBy(Fraction other) {
          ... 
        }
        public static void main(String[] args) {
            Fraction f = new Fraction(6, 9);
            Fraction g = new Fraction(-4, 6);
            System.out.println("Test of operations: ");
            System.out.println("  Add: " + f + " + " + g + " = " + f.plus(g));
            System.out.println("  Sub: " + f + " - " + g + " = " + f.minus(g));
            System.out.println("  Mul: " + f + " * " + g + " = " + f.times(g));
            System.out.println("  Div: " + f + " / " + g + " = " + f.divideBy(g));
            System.out.println("Test of predicates: ");
            System.out.print("  1. Does " + f + " equal " + g + "? ");
            System.out.println(" The answer is: " + f.equals(g));
            Fraction h = new Fraction(8, -2);
            System.out.print("  2. Is " + h + " an integer? ");
            System.out.println("The answer is: " + h.isInt());
            Fraction i, j;
            i = (f.minus(g)).times(f.plus(g));
            j = f.times(f).minus(g.times(g));
            System.out.print("  3. Does " + i + " equal " + j + "? ");
            System.out.println("The answer is: " + i.equals(j));
            System.out.print("  4. Is 5/8 greater than 2/3? The answer is: ");
            System.out.println((new Fraction(5, 8)).greaterThan(new Fraction (2, 3)));
    
        }
    }
    
    //----------------------------------------------------------------------
    
    class BankAccount {
    
        double balance; 
    
        BankAccount() { 
    
        } 
    
        BankAccount(double initialBalance) {
          ... 
        } 
    
        void withdraw(double amount) {
          ... 
        } 
    
        void deposit(double amount) {
          ... 
        } 
    
        double getBalance() {
          ... 
        } 
    
        public static void main(String[] args) {
    
            ConsoleReader c = new ConsoleReader(System.in); 
    
            System.out.println("Hello, and welcome to JavaOne Bank."); 
            System.out.println("An account will be created for you."); 
            System.out.println("What will the initial balance be?"); 
            System.out.println("Type it now: "); 
    
            BankAccount b = new BankAccount(c.readDouble()); 
    
            System.out.println("The current balance in your account is: " 
                               + b.getBalance()); 
    
            System.out.println("You now want to make a deposit. How much?"); 
            System.out.println("Type the amount here: "); 
    
            b.deposit(c.readDouble()); 
    
            System.out.println("The current balance in your account is: " 
                               + b.getBalance()); 
    
            System.out.println("You now want to make a withdrawal. How much?"); 
            System.out.println("Type it now: "); 
    
            b.withdraw(c.readDouble()); 
    
            System.out.println("The current balance in your account is: " 
                               + b.getBalance()); 
    
            System.out.println("Thanks for using class BankAccount. Good-bye!"); 
        }
    }
    
    //----------------------------------------------------------------------
    
    class Car {
    
        double fuelEfficiency;
    
        double fuel;
    
        Car(double efficiency) {
    
            fuelEfficiency = efficiency;
    
        } 
    
        void drive(double distance) {
    
            fuel -= distance / fuelEfficiency; 
    
        } 
    
        double getFuelLevel() {
    
            return fuel; 
    
        } 
    
        void tank(double extraFuel) {
    
            fuel += extraFuel; 
    
        }
    
        public static void main(String[] args) {
    
            Car myBeemer = new Car(29);
    
            System.out.println(myBeemer.getFuelLevel()); 
    
            myBeemer.tank(20); 
    
            System.out.println(myBeemer.getFuelLevel()); 
    
            myBeemer.drive(100); 
    
            System.out.println(myBeemer.getFuelLevel()); 
    
        } 
    } 
    
    //----------------------------------------------------------------------
    
    class BeerCan {
    
        double height, radius; 
    
        BeerCan(double givenHeight, double givenRadius) {
    
            height = givenHeight; 
            radius = givenRadius;
    
        }
    
        double getSurfaceArea() {
    
            return Math.PI * 2 * radius * height; 
    
        }
    
        double getVolume() {
    
            return height * Math.PI * radius * radius; 
    
        } 
    
        public static void main(String[] args) {
    
            ConsoleReader c = new ConsoleReader(System.in); 
    
            System.out.println("Please specify the height of the BeerCan."); 
    
            double height = c.readDouble(); 
    
            System.out.println("Please specify the radius of the BeerCan."); 
    
            double radius = c.readDouble(); 
    
            BeerCan b = new BeerCan(height, radius); 
    
            System.out.println("The BeerCan has been created."); 
            System.out.println("Its surface area is: " + b.getSurfaceArea()); 
            System.out.println("Its volume is: " + b.getVolume()); 
        }
    }
    
    //----------------------------------------------------------------------
    
    class Runner {
        double distance;
        String name; 
        Runner(String name) {
    	this.name = name; 
        }
        void run() {
    	this.distance += Math.random() * (12 - 10) + 10; 
    	this.distance = (int) (this.distance * 100) / 100.0; 
        }
        void report() {
    	System.out.println("                         ... " + 
    			   this.name + " now at " + 
    			   this.distance + " meters."); 
        }
    }
    
    class Olympics {
        public static void main(String[] args) {
    	Runner a = new Runner("Ben Johnson");
    	Runner b = new Runner("Carl Lewis"); 
    	System.out.println("The contest starts, " + 
    			   "we will give you updates every second."); 
    	for (int i = 1; a.distance < 100 && b.distance < 100; i++) {
    	    a.run(); 
    	    a.report(); 
    	    b.run(); 
    	    b.report(); 
    	    System.out.println("After " + i + " seconds, " +
    			       (a.distance > b.distance? a.name : b.name) + 
    			       " is in front (by " + 
    			       (int) (Math.abs(a.distance 
    					       - b.distance) * 100) / 100.0 + 
    			       " meters). "); 
    
    	}
    	System.out.println("The contest is over, and the winner is: " +
    			   (a.distance > b.distance? a.name : b.name)); 
        }  
    }
    
    //----------------------------------------------------------------------
    
    class Runner {
        double distance;
        String name; 
        int wins; 
        Runner(String name) {
    	this.name = name; 
        }
        void run() {
    	this.distance += Math.random() * (12 - 10) + 10; 
    	this.distance = (int) (this.distance * 100) / 100.0; 
        }
        void report() {
    	System.out.println("                         ... " + 
    			   this.name + " now at " + 
    			   this.distance + " meters."); 
        }
    
        void reset() {
    	this.distance = 0; 
        }
    }
    
    class More {
        public static void main(String[] args) {
    	Runner a = new Runner("Ben Johnson");
    	Runner b = new Runner("Carl Lewis"); 
    
    	for (int times = 1; times < 20; times++) {
    	    
    	    for (int i = 1; a.distance < 100 && b.distance < 100; i++) {
    		a.run(); 
    		b.run(); 
    	    }
    	    
    	    if (a.distance > b.distance) {
    		a.wins += 1; 
    		System.out.println(a.name + " wins."); 
    	    } else if (a.distance < b.distance) { 
    		b.wins += 1;
    		System.out.println(b.name + " wins.");  
    	    } else { 
    		System.out.println("This contest is a tie."); 
    	    }  
    
    	    a.reset(); 
    	    b.reset(); 
    
    	}
    
    	System.out.println(a.name + " has " + a.wins + " wins."); 
    	System.out.println(b.name + " has " + b.wins + " wins."); 
        }
    }
    
    //----------------------------------------------------------------------
    
    public class Nim {
      public static void main(String[] args) {
        Pile pile = new Pile(32);
        ConsoleReader c = new ConsoleReader(System.in);
        System.out.println("Welcome. You're playing with a pile of size: " + pile.size());
        while (pile.size() > 1) {
          int user;
          do {
            System.out.print("How many marbles do you want to take: ");
            user = c.readInt();
          } while(! pile.remove(user));
        }
      }
    }
    
    public class Pile {
      int balance;
      Pile(int initial) {
        this.balance = initial;
      }
      int size() {
        return this.balance;
      }
      boolean remove(int amount) {
        if (amount > 0 && amount <= this.size() / 2) {
          this.balance = this.balance - amount;
          System.out.println("Move is OK. Height is now: " + this.size());
          if (this.balance == 1) System.out.println("Game over. You won.");
          return true;
        } else {
          System.out.println("Not good. Try again. Pile is: " + this.size());
          return false;
        }
      }
    }
    
    //----------------------------------------------------------------------
    
    class Drunkard {
        int x, y; 
        Drunkard(int x, int y) {
    	this.x = x; 
    	this.y = y;
        } 
        void moveNorth() {
    	this.y -= 1; 
        }
        void moveEast() {
    	this.x += 1; 
        }
        void report() {
    	System.out.println("Hiccup: " + x + ", " + y); 
        } 
    } 
    
    class Four {
        public static void main(String[] args) {
    	Random generator = new Random(); 
    	Drunkard drunkard = new Drunkard(100, 100); 
    	int direction; 
    	for (int i = 0; i < 100; i++) {
    	    direction = Math.abs(generator.nextInt()) % 4; 
    
    	    if        (direction == 0) { // N
    		drunkard.moveNorth();
    
    	    } else if (direction == 1) { // E
    		drunkard.moveEast(); 
    
    	    } else if (direction == 2) { // S
    		System.out.println("Should move South."); 
    
    	    } else if (direction == 3) { // W
    		System.out.println("Should move West."); 
    
    	    } else {
    		System.out.println("Impossible!"); 
    
    	    } 
    	    drunkard.report(); 
    	} 
        }
    } 
    
    //----------------------------------------------------------------------
    
    class Game {
        public static void main(String[] args) {
    	System.out.println("Ladies and gentlemen, the Indiana Pacers!"); 
    	Player croshere = new Player("Austin Croshere", 0, 3); 
    	Player miller   = new Player("Reggie Miller", 2, 5); 
    	Player jackson  = new Player("Mark Jackson", 7, 3); 
    	Player rose     = new Player("Jalen Rose", 9, 2);
    	Player mullin   = new Player("Chris Mullin", 9, 9); 
            Ball ball = new Ball(); 
    	Basket basket = new Basket(20, 20); 
    	jackson.hands = ball; 
    	jackson.moves(1, 0); 
    	miller.moves(-2, 4); 
    	rose.moves(3, -2); 
    	jackson.passTo(rose); 
    	mullin.moves(3, 3); 
    	croshere.moves(-1, 4); 
    	rose.passTo(miller); 
    	jackson.moves(3, 3); 
    	miller.shootsTo(basket); 
    	System.out.println("Audience erupts. (Courtesy the Indiana Pacers Sports Network). "); 
        } 
    } 
    
    class Player {
        private int x;
        private int y; 
        private String name; 
        Player (String name, int x, int y) {
    	this.name = name; 
    	this.x = x;
    	this.y = y; 
    	System.out.println("Player " + this.name + 
    			   " at (" + this.x + ", " + this.y + ")"); 
        }
        Ball hands; 
        void passTo(Player other) {
    	other.hands = this.hands;
    	this.hands = null;
    	System.out.println(this.name + " sending the ball to " + other.name); 
        } 
        void moves(int dX, int dY) {
    	x = x + dX; 
    	y = y + dY; 
    	System.out.print(this.name + " moves to (" + 
                                         this.x + ", " + this.y + ")"); 
    	if (hands != null) { System.out.println(" he has the ball."); }
            else { System.out.println(); } 
        }
        void shootsTo(Basket basket) {
    	basket.inside = this.hands;
    	this.hands = null; 
    	System.out.println(this.name + " shoots... boooommm-baby!"); 
        }    
    }
    
    class Basket {
        Ball inside; 
        int x;
        int y;
        Basket(int x, int y) {
    	this.x = x;
    	this.y = y; 
        }
    }
    
    class Ball {
    
    } 
    
    //----------------------------------------------------------------------
    
    class Athlete { 
    
      String name;
      double weight;
    
      Athlete(String givenName, double givenWeight) {
        name = givenName; 
        weight = givenWeight;
      }
    
      void report() {
        System.out.println(name + ": " + weight);
      }
    
      void eat(int bagels) {
        this.report();
        System.out.println(            "My name is " + 
                                                name +
                      " and I am just about to eat " + 
                                              bagels + 
                                            " bagels."
                          );
    
        weight += bagels * 0.25;
    
        System.out.println(            "My name is " + 
                                                name +
                           " and I have just eaten " + 
                                              bagels + 
                                            " bagels."
                          );
        this.report();
      }
    
      void workOut(int minutes) {
        this.report();
        System.out.println(            "My name is " + 
                                                name +
             " and I am just about to work out for " + 
                                             minutes + 
                                           " minutes."
                          );
    
        double lostWeight = minutes / 20.0 * 0.75;
    
        weight -= lostWeight;
    
        System.out.println(            "My name is " + 
                                                name +
                        " and I am just finished a " + 
                                             minutes + 
                                  " minutes work-out."
                          );
        this.report();
      }
    }
    
    class Story {
      public static void main(String[] args) {
    
        Athlete a = new Athlete("George Foreman", 300);
        a.report();
    
        Athlete b = new Athlete("Riddick Bowe"  , 250);
        b.report();
    
        a.eat(1000);
    
        b.eat(15);
    
        b.workOut(12000);
    
        b.eat(20000);
    
        // and so on 
    
      }
    }
    
    //----------------------------------------------------------------------
    
    class Student {
    
        String name; 
    
        double totalQuizScore; 
    
        Student(String givenName) {
    
            name = givenName; 
    
        } 
    
        String getName() {
    
            return name; 
    
        } 
    
        void addQuiz(int score) {
    
            quizzes += 1; 
            totalQuizScore += score; 
    
        } 
    
        int quizzes; 
    
        double getTotalScore() {
    
            return totalQuizScore; 
    
        } 
    
        double getAverageScore() {
    
            return totalQuizScore / quizzes; 
    
        } 
    
        public static void main(String[] args) {
    
            Student a = new Student("Larry"); 
    
            a.addQuiz(10);
            a.addQuiz(9); 
            a.addQuiz(8); 
    
            System.out.println("Grade report for: " + a.getName()); 
            System.out.println("Total score: " + a.getTotalScore()); 
            System.out.println("Average score: " + a.getAverageScore()); 
    
        }
    }
    
    //----------------------------------------------------------------------
    
    import java.util.*;
    
    public class BubbleMachine {
        int balance;
        String bubbleName;
    
        public BubbleMachine(String name, int amount) {
            this.balance = amount;
            this.bubbleName = name;
        }
    
        public BubbleMachine() {
            this.balance = 100;
            this.bubbleName = "Byron";
        }
    
    
        public void createBubble() {
            int size = (int) (Math.random() * balance);
            this.balance -= size;
            System.out.println("A soap bubble was just made by " + this.bubbleName + "'s Bubble Machine.");
            System.out.println("   " + this.bubbleName + "'s Bubble Machine used " + size + " amount of soap to create this bubble.");
        }
    
        public void addSoap(int quantity) {
            this.balance += quantity;
            System.out.println(quantity + " amount of soap was just added to " + this.bubbleName + "'s Bubble Machine.");
        }
    
        public void report() {
            System.out.println(this.bubbleName + " has " + this.balance + " amount of soap in its Bubble Machine.");
        }
    
        public static void main(String[] args) {
            BubbleMachine Byron = new BubbleMachine();
            Byron.createBubble();
            Byron.report();
            Byron.addSoap(130);
            Byron.report();
            BubbleMachine Gary = new BubbleMachine("Gary", 1200);
            Byron.createBubble();
            Byron.report();
            Byron.addSoap(130);
            Byron.report();
        }
    
    }
    
    //----------------------------------------------------------------------
    
    
  12. Write code to encode and decode strings of characters according to some scheme

    This is like the Stenographer program in Lab Seven.

    Here's Encode. At the very least please explain how this works:

    class Encode {
        public static void main(String[] args) {
    	ConsoleReader console = new ConsoleReader(System.in); 
    	System.out.print("Encode> "); 
    	String line; 
    	do { 
    	    line = console.readLine(); 
    	    for (int i = 0; i < line.length(); i++) {
    		System.out.print((char)(line.charAt(i) + 1)); 
    	    }
    	    System.out.println(); 
    	    System.out.print("Encode> "); 
    	} while (! line.equals("quit")); 
        }
    }
    I am not going to provide Decode.

For each a brief description on how to proceed will be added tonight (done).

Grading
Feedback will be provided within a week, grades will be posted on-line.

Last updated: March 23, 2004 by Adrian German for A201