Second Summer 2002


Lab Notes Four: Sample problems. The Solutions.

Here are examples of solutions to the problems in the second set:

1. Write a program that asks for an initial balance amount. Create a BankAccount object with that amount. Then ask for a deposit amount and a withdrawal amount. Carry out the deposit and withdrawal, then print the remaining balance. Use ConsoleReader from Lab Notes Two, and please place your main method in the class BankAccount.
Here's a sample run of such a program:
frilled.cs.indiana.edu%javac BankAccount.java
frilled.cs.indiana.edu%java BankAccount
Hello, and welcome to JavaOne Bank.
An account will be created for you.
What will the initial balance be?
Type it now: 
-40.2
The current balance in your account is: -40.2
You now want to make a deposit. How much?
Type the amount here: 
120.3
The current balance in your account is: 80.1
You now want to make a withdrawal. How much?
Type it now: 
34
The current balance in your account is: 46.099999999999994
Thanks for using class BankAccount. Good-bye!
frilled.cs.indiana.edu%
Here's a sample solution to this problem:

/* This is the file One.java -- which contains the solution to 
the first problem in the second problem set. We just added a main 
method to the BankAccount class which goes through the sequence 
of steps that the problem is asking for. ConsoleReader class is 
also included. Notice that for both classes to be allowed to make 
up this file, with a name of One.java, we need to make sure they 
are not declared public. To run this program compile One.java
and then run java on BankAccount */ 

import java.io.*;// needed for ConsoleReader below

class BankAccount {

    double balance; 

    BankAccount() { 

    } 

    BankAccount(double initialBalance) {
        balance = initialBalance; 
    } 

    void withdraw(double amount) {
        balance = balance - amount; 
    } 

    void deposit(double amount) {
        balance = balance + amount; 
    } 

    double getBalance() {
        return balance; 
    } 

    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 ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

2. Implement a class Employee. An employee has a name (a String) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Write a small program to test your class.
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Employee
Creating a new employee.
Please type the name:
Larry Bird
Please specify the salary:
200000
New employee has been created.
Name of employee: Larry Bird
Salary: 200000.0
Thank you for testing class Employee.
frilled.cs.indiana.edu%
Here's a sample solution to this problem:
/* Second problem on the second problem set. Copy this in a file
   called Two.java then compile the file, and run Employee */ 

import java.io.*; 

class Employee {

    String name; 

    double salary; 

    Employee() {
        this.name = "Volunteer"; 
        this.salary = 0.0; 
    }

    Employee(String givenName, double initialSalary) {
        name = givenName;
        salary = initialSalary;
    } 

    String getName() {
        return name; 
    }
 
   double getSalary() {
        return salary; 
    } 

    public static void main(String[] args) {

        ConsoleReader c = new ConsoleReader(System.in); 

        System.out.println("Creating a new employee."); 
        System.out.println("Please type the name:"); 

        String name = c.readLine(); 

        System.out.println("Please specify the salary:"); 

        double salary = c.readDouble(); 

        Employee e = new Employee(name, salary); 

        System.out.println("New employee has been created."); 

        System.out.println("Name of employee: " + e.getName()); 

        System.out.println("Salary: " + e.getSalary()); 

        System.out.println("Thank you for testing class Employee."); 
    } 
} 

class ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

3. Implement a class Employee. An employee has a name (a String) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Test your program, then enhance the class by adding a method
raiseSalary(double byPercent)
that raises the employee's salary by a certain percentage.
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Employee
Creating a new employee.
Please type the name:
Michael Jordan
Please specify the salary:
300000
New employee has been created.
Name of employee: Michael Jordan
Salary: 300000.0
Raising the salary of Michael Jordan
By what percentage (e.g., 10, 20, etc.)?
10.5
Name of employee: Michael Jordan
Current salary: 331500.0
Thank you for testing class Employee.
frilled.cs.indiana.edu%
Here's a sample solution to the problem:
/* Third problem on the second problem set. Copy this in a file
   called Three.java then compile the file, and run Employee */ 

import java.io.*; 

class Employee {

    String name; 

    double salary; 

    Employee() {
        name = "Volunteer"; 
        salary = 0.0; 
    }

    Employee(String givenName, double initialSalary) {
        name = givenName;
        salary = initialSalary;
    } 

    String getName() {
        return name; 
    }

    double getSalary() {
        return salary; 
    } 

    void raiseSalary(double percentage) {
        salary += 0.01 * percentage * salary; 
    } 

    public static void main(String[] args) {

        ConsoleReader c = new ConsoleReader(System.in); 

        System.out.println("Creating a new employee."); 
        System.out.println("Please type the name:"); 

        String name = c.readLine(); 

        System.out.println("Please specify the salary:"); 

        double salary = c.readDouble(); 

        Employee e = new Employee(name, salary); 

        System.out.println("New employee has been created."); 
        System.out.println("Name of employee: " + e.getName()); 
        System.out.println("Salary: " + e.getSalary()); 
        System.out.println("Raising the salary of " + e.getName()); 
        System.out.println("By what percentage (e.g., 10, 20, etc.)?"); 

        double percentage = c.readDouble(); 

        e.raiseSalary(percentage); 

        System.out.println("Name of employee: " + e.getName()); 
        System.out.println("Current salary: " + e.getSalary()); 
        System.out.println("Thank you for testing class Employee."); 
    } 
} 

class ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

4. Implement a class Car with the following properties. A car has a certain fuel efficiency (measured in miles per gallon or liters per km -- pick one) and a certain amount of fuel in the gas tank. The efficiency is specified in the constructor,and the initial fuel level is 0. Supply a method drive that simulates driving the car for a certain distance, reducing the fuel level in the gas tank, and methods getFuelLevel, returning the current fuel level, and tank, to tank up.
Sample usage of the class:
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()); 
} 
Should produce:
frilled.cs.indiana.edu%java Car
0.0
20.0
16.551724137931036
Here's a sample solution to this problem:
/* Fourth problem on the second problem set. Copy this to a file
   called Four.java then compile the file, and run java Car -- the
   examples above all use ConsoleReader feel free to use it that way, 
   the test program below is minimal as in the text of the problem. */ 
 
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()); 

    } 
} 

5. Change the purse program Coins6 (page 123) to ask the user to supply coins in a different currency. For example, you can use the following collection of German coins:
new Coin(0.01, "Pfennig");
new Coin(0.1, "Groschen"); 
new Coin(1.0, "Mark"); 
What changes did you have to make? What changes would you have to make to the Coins4 (page 82) program to change the currency? Which is easier? (Answer these questions in a comment that you can include either at the top or at the bottom of the program you submit).

Here's a sample run of such a program:
frilled.cs.indiana.edujava Coins6
Hello and welcome to Coins6 program.
Please specify four types of coins. Anything goes.
Name of coin1 (e.g. groschen, mark, pfennig etc.):
pfennig
Value of pfennig (i.e., 0.01, 0.10, 0.25, etc.): 
0.01
Coin pfennig (0.01) created.
------------------------------------
Name of coin2:
groschen
Value of groschen: 
0.1
Coin groschen (0.1) created.
------------------------------------
Name of coin3:
mark
Value of mark: 
1
Coin mark (1.0) created.
------------------------------------
Name of coin4:
germanNickel
Value of germanNickel: 
0.05
Coin germanNickel (0.05) created.
------------------------------------
 How many pfennig do you have?
2
 How many groschen do you have?
3
 How many mark do you have?
1
 How many germanNickel do you have?
4
The total value is: 1.52
frilled.cs.indiana.edu
Here's a sample solution to this problem:
/* This is the solution to the fifth problem on the second
   problem set. Notice that classes Coin, Purse, and the test
   program Coins6 are in the book pages 120-123. We just made
   a few changes here to allow for the specification of four
   any-type kind of coins. ConsoleReader is included for the same
   reason. Comments that answer the question in the text of 
   the problem are included. The file name is Five.java and 
   to run this you need to compile Five.java and then run 
   java on Coins6 which has the main method. */

import java.io.*; 

class Coin {

    public Coin(double aValue, String aName) {

        value = aValue; 
        name = aName; 

    } 

    public double getValue() {

        return value; 

    } 

    public String getName() {
        return name;
    } 

    private double value; 
    private String name; 

} 

class Purse { 

    public Purse() {

        total = 0; 

    } 

    public void addCoins(int coinCount, Coin coinType) {

        double value = coinCount * coinType.getValue(); 
        total += value;

    } 

    public double getTotal() {

        return Math.round(total * 100) / 100.0;

    }

    private double total; 
} 

class Coins6 {

    public static void main(String[] args) {

        Purse thePurse = new Purse(); 

        ConsoleReader console = new ConsoleReader(System.in); 

        System.out.println(
          "Hello and welcome to Coins6 program.");

        System.out.println(
          "Please specify four types of coins. Anything goes."); 

        System.out.println(
          "Name of coin1 (e.g. groschen, mark, pfennig etc.):");

        String name = console.readLine(); 

        System.out.println(
          "Value of " + name + " (i.e., 0.01, 0.10, 0.25, etc.): "); 

        double value = console.readDouble(); 

        Coin coin1 = new Coin(value, name); /* 
              This is the only thing we need to do to change the types
              of coins that we create. Compared with program Coins4 it 
              results in big savings of time and increased reliability
              as in Coins4 we need to update all but three lines in the
              program, messages and named constants everywhere. 
                                             */

        System.out.println("Coin " + coin1.getName() + 
                           " (" + coin1.getValue() + ") created.");
        System.out.println("------------------------------------"); 

        System.out.println("Name of coin2:");

        name = console.readLine(); 

        System.out.println("Value of " + name + ": "); 

        value = console.readDouble(); 

        Coin coin2 = new Coin(value, name); 

        System.out.println("Coin " + coin2.getName() + 
                           " (" + coin2.getValue() + ") created.");
        System.out.println("------------------------------------"); 

        System.out.println("Name of coin3:");
        name = console.readLine(); 
        System.out.println("Value of " + name + ": "); 
        value = console.readDouble(); 
        Coin coin3 = new Coin(value, name); 
        System.out.println("Coin " + coin3.getName() + 
                           " (" + coin3.getValue() + ") created.");
        System.out.println("------------------------------------"); 
        System.out.println("Name of coin4:");
        name = console.readLine(); 
        System.out.println("Value of " + name + ": "); 
        value = console.readDouble(); 
        Coin coin4 = new Coin(value, name); 
        System.out.println("Coin " + coin4.getName() + 
                           " (" + coin4.getValue() + ") created.");
        System.out.println("------------------------------------"); 

        System.out.println(" How many " + coin1.getName() + 
                           " do you have?");
        int coin1Count = console.readInt(); 

        System.out.println(" How many " + coin2.getName() + 
                           " do you have?");
        int coin2Count = console.readInt(); 

        System.out.println(" How many " + coin3.getName() + 
                           " do you have?");
        int coin3Count = console.readInt(); 

        System.out.println(" How many " + coin4.getName() + 
                           " do you have?");
        int coin4Count = console.readInt(); 

        thePurse.addCoins(coin1Count, coin1); 
        thePurse.addCoins(coin2Count, coin2); 
        thePurse.addCoins(coin3Count, coin3); 
        thePurse.addCoins(coin4Count, coin4); 

        System.out.println("The total value is: " +
                           thePurse.getTotal()); 
    }
}

class ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

6. Add a method
askForCoins(Coin coinType)
to the Purse class that asks the user how many coins of that type to add to the purse and that updates the coin count. Then change Coins6 (page 123) and test your new method.
Here's a sample run of such a program:
frilled.cs.indiana.edu%java Coins6
Hello and welcome to Coins6 program.
How many pennies can you donate?
3
How many dimes can you donate?
4
How many quarters can you donate?
5
How many dollars can you donate?
6
The total value is: 7.68
frilled.cs.indiana.edu%
Here's a sample solution to this problem:
/* This is the solution to the sixth problem on the second 
   problem set. Please compare this to the program above. 
   Adding one method to Purse simplifies the collection 
   mechanism as we can delegate more of the user interface 
   to objects of class Purse. */

import java.io.*; 

class Coin {

    public Coin(double aValue, String aName) {

        value = aValue; 
        name = aName; 

    } 

    public double getValue() {
        return value; 
    } 

    public String getName() {
        return name;
    } 

    private double value; 

    private String name; 
} 

class Purse { 

    public Purse() {

        total = 0; 

    } 

    public void addCoins(int coinCount, Coin coinType) {

        double value = coinCount * coinType.getValue(); 

        total += value;

    } 

    public double getTotal() {

        return Math.round(total * 100) / 100.0;

    }

    private double total; 

    void askForCoins(Coin coinType) {

        ConsoleReader console = new ConsoleReader(System.in); 

        System.out.println("How many " + coinType.getName() + 
                           " can you donate?");

        int coinCount = console.readInt();

        addCoins(coinCount, coinType); 

    } 

} 

class Coins6 {

    public static void main(String[] args) {

        Purse thePurse = new Purse(); 

        System.out.println("Hello and welcome to Coins6 program."); 

        thePurse.askForCoins(new Coin(0.01, "pennies")); 
        thePurse.askForCoins(new Coin(0.1, "dimes")); 
        thePurse.askForCoins(new Coin(0.25, "quarters")); 
        thePurse.askForCoins(new Coin(1.00, "dollars")); 

        System.out.println("The total value is: " +
                           thePurse.getTotal()); 
    }
}

class ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

7. Implement a class Student. For the purpose of this exercise, a student has
  • a name and
  • a total quiz score
Supply an appropriate constructor and methods
  • getName()
  • addQuiz(int score)
  • getTotalScore(), and
  • getAverageScore()

To compute the latter, you also need to store the number of quizzes that the student took.

Here's a sample run of such a program:
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()); 
}
Should produce:
frilled.cs.indiana.edu%java Student
Grade report for: Larry
Total score: 27.0
Average score: 9.0
frilled.cs.indiana.edu%
Here's a sample solution to this problem:
/* This is file Seven.java containing the solution to problem 
seven on the second set of problems. To run this compile the file
Seven.java and then run java Student. Notice the instance variable 
quizzes which is only hinted at in the text of the problem. */

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()); 

    }
}

8. Implement a class Product. A product has
  • a name and
  • a price
For example
new Product("Toaster", 29.95)
Supply methods
  • printProduct()
  • getPrice(), and
  • setPrice()
Write a program that
  • makes two products,
  • prints them,
  • reduces their prices by $5.00, and then
  • prints them again
Here's a sample run of such a program:
public static void main(String[] args) {
    Product a = new Product("Toaster", 29.95); 
    Product b = new Product("Phone", 35.55); 
    a.printProduct(); 
    a.setPrice(a.getPrice() - 5.00); 
    a.printProduct(); 
    b.printProduct(); 
    b.setPrice(b.getPrice() - 5.00); 
    b.printProduct(); 
} 
Should produce:
frilled.cs.indiana.edu%java Product
Product name: Toaster
Product price: 29.95
------------------------------
Product name: Toaster
Product price: 24.95
------------------------------
Product name: Phone
Product price: 35.55
------------------------------
Product name: Phone
Product price: 30.549999999999997
------------------------------
frilled.cs.indiana.edu%
Here's a sample solution to this problem:
/* This is the solution to problem eight on the second set
of programs. The name of the file is Eight.java -- compile
it, then run java on Product (which has the main method). */ 

class Product {

    String name; 

    double price; 

    Product(String givenName, double givenPrice) {

        name = givenName; 

        price = givenPrice; 

    } 

    void printProduct() {

        System.out.println("Product name: " + name); 
        System.out.println("Product price: " + price); 
        System.out.println("------------------------------"); 

    } 

    double getPrice() {

        return price; 

    } 

    void setPrice(double newPrice) {

        price = newPrice; 

    }

    public static void main(String[] args) {

        Product a = new Product("Toaster", 29.95); 

        Product b = new Product("Phone", 35.55); 

        a.printProduct(); 
        a.setPrice(a.getPrice() - 5.00); 
        a.printProduct(); 

        b.printProduct(); 
        b.setPrice(b.getPrice() - 5.00); 
        b.printProduct(); 

    } 
}

9. Implement a class Circle that has methods
  • getArea() and
  • getCircumference()
In the constructor, supply the radius of the circle.
Here's a sample run of such a program:
public static void main(String[] args) {
    ConsoleReader c = new ConsoleReader(System.in); 
    System.out.println("Please specify the radius of your circle:"); 
    Circle a = new Circle(c.readDouble()); 
    System.out.println("Circle created. "); 
    System.out.println("Area: " + a.getArea()); 
    System.out.println("Circumference: " + a.getCircumference()); 
    System.out.println("Good-bye!"); 
}
Should produce:
frilled.cs.indiana.edu%java Circle
Please specify the radius of your circle:
1.0
Circle created. 
Area: 3.141592653589793
Circumference: 6.283185307179586
Good-bye!
frilled.cs.indiana.edu%java Circle
Please specify the radius of your circle:
3.14
Circle created. 
Area: 30.974846927333928
Circumference: 19.729201864543903
Good-bye!
frilled.cs.indiana.edu%
Here's a sample solution to this problem:
/* This is the solution to problem nine on the second set 
of problems. Copy this in a file called Nine.java and then
compile Nine.java -- then run Circle. ConsoleReader has been
included for the user of your program to specify the radius
of the circle that (s)he is going to create interactively. */ 

import java.io.*; 

class Circle {

    double radius;

    Circle (double givenRadius) {

        radius = givenRadius; 

    } 

    double getArea() {

        return Math.PI * radius * radius;

    } 

    double getCircumference() {

        return Math.PI * radius * 2;   

    }

    public static void main(String[] args) {

        ConsoleReader c = new ConsoleReader(System.in); 

        System.out.println("Please specify the radius of your circle:"); 

        Circle a = new Circle(c.readDouble()); 

        System.out.println("Circle created. "); 
        System.out.println("Area: " + a.getArea()); 
        System.out.println("Circumference: " + a.getCircumference()); 
        System.out.println("Good-bye!"); 
    }
}

class ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

10. Implement a class BeerCan with methods
  • getSurfaceArea() and
  • getVolume()
In the constructor, supply the height and radius of the can.
Here's a sample run of such a program:
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()); 
}
Could produce:
frilled.cs.indiana.edu%java BeerCan
Please specify the height of the BeerCan.
2.5
Please specify the radius of the BeerCan.
1.0
The BeerCan has been created.
Its surface area is: 15.707963267948966
Its volume is: 7.853981633974483
frilled.cs.indiana.edu%java BeerCan
Please specify the height of the BeerCan.
2
Please specify the radius of the BeerCan.
1
The BeerCan has been created.
Its surface area is: 12.566370614359172
Its volume is: 6.283185307179586
frilled.cs.indiana.edu%
Here's a sample solution to this problem:
/* This is the solution to problem ten on the second problem 
set. Put the code in a file called Ten.java and compile the 
file. Then run java BeerCan as the BeerCan class defines the 
main method. ConsoleReader class included for convenience. */ 

import java.io.*; 

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 ConsoleReader { 
    public ConsoleReader(InputStream inStream) { 
        reader = new BufferedReader(
                   new InputStreamReader(
                     inStream));     
    }
    public String readLine() { 
        String inputLine = "";
        try {
            inputLine = reader.readLine(); 
        } catch (IOException e) {
            System.out.println(e); 
            System.exit(1); 
        } 
        return inputLine; 
    }
    public int readInt() { 
        String inputString = readLine(); 
        int n = Integer.parseInt(inputString); 
        return n; 
    }
    public double readDouble() { 
        String inputString = readLine(); 
        double x = Double.parseDouble(inputString); 
        return x; 
    } 
    private BufferedReader reader; 
}

So, as always, I hope you found this useful.


Last updated: Jun 16, 2002 by Adrian German for A201