Skip to main content

L02

SodaCan.java

/**
 * Constructor and methods for a soda can object
 * 
 * @author Brandon
 * @version 1/1/1990
 */
public class SodaCan {
  private double r; // soda can radius
  private double h; // soda can height

  public SodaCan(double radius, double height) {
    r = radius;
    h = height;
  }

  public double findSurfaceArea() {
    return 2.0 * (22.0 / 7.0) * r * h + 2.0 * (22.0 / 7.0) * r * r; // compute the surface area A=2πrh+2πr^2
  }

  public double findVolume() {
    return (22.0 / 7.0) * r * r * h; // compute the volume V=πr^2h
  }
}

SodaCanTest.java

import java.util.Scanner;

/**
 * A class to test a SodaCan
 * 
 * @author Brandon
 * @version 1/1/1990
 */
public class SodaCanTest {
    public static void main(String[] args) {
        Scanner myScanner = new Scanner(System.in);

        System.out.print("Enter the radius: ");
        String answer = myScanner.nextLine();
        double radius = Double.parseDouble(answer); // convert using the parseDouble method

        System.out.print("Enter the height: ");
        answer = myScanner.nextLine();
        double height = Double.parseDouble(answer); // convert using the parseDouble method

        // instantiate a soda can object using the radius and height above
        // display the surface area to three decimal digits using printf
        // display the volume to three decimal digits using printf
        SodaCan mySodaCan = new SodaCan(radius, height);

        System.out.printf("The surface area of the can is %.3f", mySodaCan.findSurfaceArea());
        System.out.println(); // this is to add a new line between the strings
        System.out.printf("The volume of the can is %.3f", mySodaCan.findVolume());
    }
}