Creating a class for an object - java

I'm creating a class that will create a Pizza object. It takes into account its size (diameter in inches), the number of slices, the cost of the pie, and the type of pizza.
This is my first time doing such a thing, so I've run into some snafus.
Here is the code for the class Pizza:
class Pizza
{
//instance variables
int size;
int slices;
int pieCost;
String typeOfPizza;
//constructors
Pizza (String typeOfPizza)
{
System.out.println (typeOfPizza);
}
Pizza ()
{
System.out.println ("pizza");
}
Pizza (int s, int sl, int c)
{
size = s;
slices = sl;
pieCost = c;
typeOfPizza = "????";
}
Pizza (String name, int s, int sl, int c)
{
typeOfPizza = name;
size = s;
slices = sl;
pieCost = c;
}
//behavior
double areaPerSlice(int size, int slices)
{
double wholeArea = Math.PI * Math.pow ((size/2), 2);
double sliceArea = wholeArea/slices;
return sliceArea;
}
double costPerSlice (double pieCost, int slices)
{
double sliceCost = pieCost/slices;
return sliceCost;
}
double costPerSquareInch (double sliceCost, double sliceArea)
{
double costPerSquareInch = sliceCost/sliceArea;
}
String getName(String name)
{
String typeOfPizza = name;
return typeOfPizza;
}
}
Here is the code for the main method that calls on the Pizza class:
class PizzaTest
{
public static void main (String [] args)
{
String typeOfPizza = "Cheese";
int size = 10; //in inches, referring to the diameter of the pizza
int numberOfSlices = 10; //number of slices
int costOfPie = 20;
Pizza myPizza = new Pizza (typeOfPizza, size, numberOfSlices, costOfPie);
System.out.printf ("Your %s pizza has %.2f square inches per slice.\n", myPizza.getName(),
myPizza.areaPerSlice() );
System.out.printf ("One slice costs $%.2f, which comes to $%.3f per square inch.\n",
myPizza.costPerSlice(), myPizza.costPerSquareInch());
}
}
Essentially, the output should print the following:
Your Pepperoni pizza has 20.11 square inches per slice.
One slice costs $1.05, which comes to $0.052 per square inch.
The values can be ignored, they're from an example with different parameters. When I go to compile this program, I get the following errors:
getName(java.lang.String) in Pizza cannot be applied to ()
System.out.printf ("Your %s pizza has %.2f square inches per slice.\n", myPizza.getName(),
^
PizzaTest.java:20: areaPerSlice(int,int) in Pizza cannot be applied to ()
myPizza.areaPerSlice() );
^
PizzaTest.java:23: costPerSlice(double,int) in Pizza cannot be applied to ()
myPizza.costPerSlice(), myPizza.costPerSquareInch());
^
PizzaTest.java:23: costPerSquareInch(double,double) in Pizza cannot be applied to ()
myPizza.costPerSlice(), myPizza.costPerSquareInch());
Any input as to how I can fix this? Thanks for helping out a beginning programmer!

Change
String getName(String name)
{
String typeOfPizza = name;
return typeOfPizza;
}
to
String getName()
{
return typeOfPizza;
}
and
double costPerSquareInch (double sliceCost, double sliceArea){
double costPerSquareInch = sliceCost/sliceArea;
}
to
double costPerSquareInch (double sliceCost, double sliceArea){
return costPerSquareInch = sliceCost/sliceArea;
}
and
System.out.printf ("Your %s pizza has %.2f square inches per slice.\n", myPizza.getName(),
myPizza.areaPerSlice() );
System.out.printf ("One slice costs $%.2f, which comes to $%.3f per square inch.\n",
myPizza.costPerSlice(costOfPie,numberOfSlices), myPizza.costPerSquareInch(sliceCost,sliceArea));
to
System.out.printf ("Your %s pizza has %.2f square inches per slice.\n", myPizza.getName(),
myPizza.areaPerSlice(size, numberOfSlices) );
System.out.printf ("One slice costs $%.2f, which comes to $%.3f per square inch.\n",
myPizza.costPerSlice(costOfPie,numberOfSlices), myPizza.costPerSquareInch(sliceCost,sliceArea));

Your function takes a non optional string.
String getName(String name)
{
String typeOfPizza = name;
return typeOfPizza;
}
Should be two functions
String getName() { // needed a string before.
return typeOfPizza;
}
void setName(String name) {
typeOfPizza = name;
}
Also, you should probably call that field name or those method(s) should be getTypeOfPizza and setTypeOfPizza.

the errors say it all...
double areaPerSlice(int size, int slices)
{
double wholeArea = Math.PI * Math.pow ((size/2), 2);
double sliceArea = wholeArea/slices;
return sliceArea;
}
System.out.printf ("Your %s pizza has %.2f square inches per slice.\n", myPizza.getName(),
myPizza.areaPerSlice() );
in the method definition, you are taking 2 args... but while calling you are using 0 arguments... THIS APPLIES FOR OTHER ERRORS ALSO.

problem
Your function is asking for a parameter.As you don't have function getName with single parameter
Solution
You have to define a method like
String getName( )
{
return typeOfPizza;
}
Same you have to do for these calls also.
myPizza.areaPerSlice()
myPizza.costPerSlice()
myPizza.costPerSquareInch()

I don't think your Pizza class will compile.
double costPerSquareInch (double sliceCost, double sliceArea){
double costPerSquareInch = sliceCost/sliceArea;
// missing return.
}
First make that one correct.
Then
myPizza.getName() // need input argument as String
Then this should as
myPizza.getName("inputString");
Also other two has same input argument issues.
myPizza.areaPerSlice()// two int input arguments.
Corrected as
myPizza.areaPerSlice(1,2);
Next one
myPizza.costPerSlice();// double and int input arguments.
correct as
myPizza.costPerSlice(2.0,2);
Finally
myPizza.costPerSquareInch() // two double input arguments.
Corrected as
myPizza.costPerSquareInch(2.0,1.0) ;

public class Pizza
{
//instance variables
pirvate int size;
private int slices;
private int pieCost;
private String typeOfPizza;
//constructors
public Pizza (String typeOfPizza)
{
System.out.println (typeOfPizza);
}
public Pizza ()
{
System.out.println ("pizza");
}
public Pizza (int size, int slices, int pieCost)
{
this.size = size;
this.slices = slices;
this.pieCost = pieCost;
typeOfPizza = "????";
}
public Pizza (String typeOfPizza, int size, int slices, int pieCost)
{
this.typeOfPizza = typeOfPizza
this.size = size;
this.slices = slices;
this.pieCost = pieCost;
}
//behavior
public double areaPerSlice(int size, int slices)
{
double wholeArea = Math.PI * Math.pow ((size/2), 2);
double sliceArea = wholeArea/slices;
return sliceArea;
}
public double costPerSlice (double pieCost, int slices)
{
double sliceCost = pieCost/slices;
return sliceCost;
}
public double costPerSquareInch (double sliceCost, double sliceArea)
{
double costPerSquareInch = sliceCost/sliceArea;
}
public String getName(String name)
{
String typeOfPizza = name;
return typeOfPizza;
}
}
class PizzaTest
{
public static void main (String [] args)
{
String typeOfPizza = "Cheese";
int size = 10; //in inches, referring to the diameter of the pizza
int numberOfSlices = 10; //number of slices
int costOfPie = 20;
Pizza myPizza = new Pizza (typeOfPizza, size, numberOfSlices, costOfPie);
System.Out.Printf ("Your"+myPizza.getName()+" pizza has "+myPizza.areaPerSlice() +".2f square inches per slice.\n");
System.Out.Printf ("One slice costs "+myPizza.costPerSlice()+".2f, which comes to "+myPizza.costPerSquareInch()+".3f per square inch.\n");
}
}
Hope this will help you.

Related

I can't seem to figure out why I keep getting true when I clearly overridden the equality method

I'm trying to figure this out but I can't seem to get it to compare correctly.
As I try to setup the code whenever I run it the result would end up becoming True when I need it to produce a false test as well. Extensive testing shows it to be always true and I have no idea how to produce a false on it.
import java.util.Scanner;
public class LandTract
{
// instance variables
private static double length , width, area;
/**
* Constructor for objects of class LandTract
*/
public LandTract(double length, double width, double area)
{
// initialise instance variables
length = 0;
width = 0;
}
public LandTract(double length, double width)
{
this.length = length;
this.width = width;
}
public void setLength(double length)
{
this.length = length;
}
public double getLength()
{
return length;
}
public void setWidth(double width)
{
this.width = width;
}
public double getWidth()
{
return width;
}
public double getArea()
{
return area = length * width;
}
public String toString()
{
String str = "Length: " + length + "\nWidth: " + width;
return str;
}
public boolean equals(Object obj)
{
LandTract land = (LandTract) obj;
if (this.length != land.length)
return false;
if (this.width != land.width)
return false;
if (this.area != land.area)
return false;
return true;
}
public static void main(String[] args)
{
Scanner key = new Scanner(System.in);
System.out.print("Enter the length of the first tract of land: ");
length = key.nextDouble();
key.nextLine();
System.out.print("Enter the width of the first tract of land: ");
width = key.nextDouble();
key.nextLine();
LandTract land1 = new LandTract(length , width);
System.out.println("The area of the first tract of land is " + land1.getArea());
System.out.println();
System.out.print("Enter the length of the second tract of land: ");
length = key.nextDouble();
key.nextLine();
System.out.print("Enter the width of the second tract of land: ");
width = key.nextDouble();
key.nextLine();
LandTract land2 = new LandTract(length, width);
System.out.println("The area of the second tract of land is " + land2.getArea());
System.out.println();
if (land1.equals(land2))
System.out.println("Both tracts of land are the same size.");
else
System.out.println("They are different sizes.");
}
}
The best example for a confusing & ironically erroneous comment:
// instance variables
private static double length , width, area;
The program works much better, when you:
(Really) Introduce instance variables:
private double length , width, area;
Fix compiler problems in main method (by declaring local variables with the same identifier ..no good style but quick):
public static void main(String[] args) {
double length, width;
// ...
}
The problem here is that the values being compared (length, width, and area) are static fields, not instance fields. This means that any reference to them will use the same global value, regardless of which instance of the class is referencing them.
Of particular relevance, this.length != land.length in the equals method will always return true, since both this.length and land.length will refer to the same value. (Note that this guarantee is no longer true if multiple threads are involved, but that's not the case with this example.)
This also means that any call to a constructor or a setter will set the shared static fields, overwriting the value previously written when calling a setter or constructor on another instance. For instance, the length, width constructor will overwrite the static length & width fields, and the setLength method will overwrite the static length field.
public LandTract(double length, double width)
{
this.length = length;
this.width = width;
}
public void setLength(double length)
{
this.length = length;
}
The fix is to change these fields to instance fields, rather than static ones:
public class LandTract
{
private double length, width, area;
// [...]
}

Design and implement a Purse Class, Coin Class, and a driver by working with Arrays of objects and Classes

Purse Class:
a. There will be an array of Coin objects (using the Coin Class) and a parallel array of integer counts. There should be single variables that hold the count of Coin objects added so far, total number of coins and total value in the purse.
b. The constructor should set the dimension of the arrays to be 10 and set the single instance variables to zero.
c. Three accessors are needed: count of Coin objects added so far, the total count of all the coins, and the total value in the purse.
d. The toString() method should output the values for each Coin in the Purse along with its count and value (count * Coin Value).
e. There will be an add() method that takes in both a Coin object and a count of how many are being added to the Purse. Place the Coin and count in the next available position in the parallel arrays. The total count and value in the purse should be incremented.
I wrote the Coin Class and Purse Class, but there is a glitch in the Purse Class because it is not counting the type of coins or the number of coins properly.
Coin Class:
import java.text.NumberFormat;
public class Coin {
private String name; //instance variable (a)
private double value;
private int year;
//Default Constructor (b)
public Coin(){
String name = " ";
double value = 0.0;
int year = 0;
}
//Parametrized Constructor (c)
public Coin(String name, double value, int year){
this.name = name;
this.value = value;
this.year = year;
}
//Accessors(d)
public String getName(){
return this.name;
}
public double getValue(){
return this.value;
}
public int getYear(){
return this.year;
}
//Mutators(d)
public void setName(String newName){
this.name = newName;
}
public void setValue(double newValue){
this.value = newValue;
checkValue();
}
public void setYear(int newYear){
this.year = newYear;
checkYear();
}
//Helper Method(e)
public void checkValue(){
if (value < 0.0){
this.value = 0.0;
}
}
//Helper Method (f)
public void checkYear(){
if((year >= 1900) || (year <= 2018)){
this.year = 0;
}
}
//toString method (g)
public String toString(){
String str = "Coin:" + this.name;
NumberFormat fmt = NumberFormat.getCurrencyInstance();
str += "\tvalue:" + fmt.format(this.value);
str += "\tyear:";
if (year!= 0)
str += this.year;
else
{
str += "Unknown";
}
return str;
}
}
Purse Class:
import java.text.NumberFormat;
public class Purse {
//a
private Coin[] coins;
private int[]counts;
private int coinCount;
private double totalValue;
private int totalCount;
//b (Constructor)
public Purse(){
coins = new Coin[10];
counts = new int[10];
coinCount = 0;
totalValue = 0.0;
totalCount = 0;
}
//c
public int getCoinCount(){
return coinCount;
}
public int getTotalCount(){
return totalCount;
}
public double getTotalValue(){
return totalValue;
}
//d (toString() method)
public String toString(){
String result = " ";
NumberFormat fmt = NumberFormat.getCurrencyInstance();
for(int i = 0; i<coinCount; i++){
result += fmt.format(counts[i] * coins[i].getValue())+coins[i]+counts[i];
}
return result;
}
//e
public void addCoin(Coin c,int n){
coins[coinCount]=c;
counts[coinCount]=n;
coinCount++;
totalCount += n;
totalValue += (n * c.getValue());
}
}
Driver:
public class CoinDriver {
public static void main(String[] args) {
Coin p = new Coin("Penny", 0.01, 2001);
Coin n = new Coin("Nickel", 0.05, 2001);
Coin d = new Coin("Dime", 0.10, 2001);
Coin q = new Coin("Quarter", 0.25, 2001);
Coin l = new Coin("Loonie", 1.00, 2001);
Coin t = new Coin ("Toonie", 2.00, 2001);
Purse purse = new Purse();
System.out.print("There are: " +purse.getCoinCount() + "types of coins, a total of:" + purse.getTotalCount()+ "coins, worth:" + purse.getTotalValue());
System.out.print(purse);
purse.addCoin(p,3);
purse.addCoin(n,5);
purse.addCoin(d,7);
System.out.print("There are: " +purse.getCoinCount() + "types of coins, a total of:" + purse.getTotalCount()+ "coins, worth:" + purse.getTotalValue());
System.out.print(purse);
}
}
The final Results should include the number of coins in the purse, the types of coins (total of), and the value of all the coins.

Testing my program?

I already have the class I need to implement in to my code. The instructions are: Code a testing program/class. This should construct or instantiate objects of the class you coded in step #1. Your testing program should call every method to make sure they work. You should construct at least two objects – one with the default constructor and one with the “other” constructor. For the second scenario, ask the user what values for (radius and) height. You may use any input and output that you want for this.
This is what I have so far and I'm stuck:
public class Cube
{
private double height;
public Cube(){
height = 1.0;
}
public Cube(double h){
height = h;
}
public double getHeight(){
return height;
}
public void setHeight(double h){
height = h;
}
public double calcVolume() {
return height*height*height;
}
public double calcSurface(){
return height*height*6;
}
public String toString(){
return this.toString();
}
public boolean equals(Cube c){
return (c.getHeight() == this.height);
}
}
import java.util.*
public class TestTheCube
{
public static void main(String[] args)
{
Cube cube1 = new Cube();
Scanner kb = new Scanner(System.in);
System.out.print("Enter a height as a positive number");
double height = kb.nextDouble();
Cube cube2 = new Cube(height);
System.out.println(
}
}
I've invoked calcVolume() of cube1 and cube2.
Cube cube1 = new Cube();
Scanner kb = new Scanner(System.in);
System.out.print("Enter a height as a positive number");
double height = kb.nextDouble();
Cube cube2 = new Cube(height);
System.out.println("Cube 1's volume = "+cube1.calcVolume());
System.out.println("Cube 2's volume = "+cube2.calcVolume());
.....//repeat for every instance method you have.

Classes and Objects. Getting 0.0 as answer when calculating price. - JAVA

I'm working out a question from a labsheet but i'm only getting 0.0 as answer when running the program. I can't find out what's wrong please help.
The question:
Implement a class Pizza with attribute diameter (in cm), cost_sq_cm (cost per square cm) and area. Its methods are:
• Constructor to create an object of type Pizza with a given diameter and given price_sq_cm.
• Mutator and accessor methods for diameter and cost_sq_cm.
• calcArea to calculate the area of a given pizza.
• getPrice to calculate and return the price of a pizza.
Write a class TestPizza with a main method that declares an object of type Pizza with a user inputted diameter and user-­‐inputted cost_sq_cm of a circular pizza, and display the price of the pizza.
The Pizza class:
package Number3;
public class Pizza {
private int diameter;
private float cost_sq_cm;
private double area;
private double price;
public Pizza() //default constructor
{
diameter = 0;
cost_sq_cm = 0;
area = 0;
price = 0;
}
public Pizza(int d,float cost,double a,double p) //overloaded constructor
{
d = diameter;
cost = cost_sq_cm;
a = area;
p = price;
}
public void Constructor() //method
{
Pizza P = new Pizza();
}
public void setDiameter(int d) //mutator
{
d = diameter;
}
public int getDiameter() //accessor
{
return diameter;
}
public void setCost(float c)
{
c = cost_sq_cm;
}
public float getCost()
{
return cost_sq_cm;
}
public double calcArea()
{
area = 3.142 * (diameter * diameter);
return area;
}
public double getPrice()
{
price = area * cost_sq_cm;
return price;
}
public void display()
{
System.out.print("The area is: "+this.price);
}
}
TestPizza:
package Number3;
import java.util.Scanner;
public class TestPizza {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float area = 0;
Pizza P = new Pizza();
int d; float c,a = 0;
System.out.print("Enter a value for the diameter: ");
d = input.nextInt();
P.setDiameter(d);
System.out.print("Enter a value for the cost: ");
c = input.nextFloat();
P.setCost(c);
P.display();
}
}
I'm new to JAVA. Please be lenient.
You should multiply cost per square centimeter times area to get price. You'll get zero if either one is equal to zero. I see where you've set diameter, but not area.
You set diameter, but you don't calculate area when you set it.
public void setDiameter(int d) //mutator; lose this comment. worthless clutter.
{
d = diameter;
area = calcArea();
}
I'd recommend following the Java idiom. Don't write a display() method; better to override toString().
I'd write it this way:
package cruft;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Pizza
* #author Michael
* #link https://stackoverflow.com/questions/28658669/classes-and-objects-getting-0-0-as-answer-when-calculating-price-java
* #since 2/22/2015 12:27 PM
*/
public class Pizza {
private static final int DEFAULT_DIAMETER = 38;
private static final double DEFAULT_COST = 15.0;
private static final double DEFAULT_COST_PER_AREA = 0.013226; // 15 euro for a 38 cm diameter pizza
private static final NumberFormat DEFAULT_FORMAT = new DecimalFormat("#.####");
private final int diameter;
private final double costPerArea;
private final double price;
public static void main(String[] args) {
int diameter = ((args.length > 0) ? Integer.valueOf(args[0]) : DEFAULT_DIAMETER);
double costPerArea = ((args.length > 1) ? Double.valueOf(args[1]) : DEFAULT_COST_PER_AREA);
Pizza pizza = new Pizza(diameter, costPerArea);
System.out.println(pizza);
}
public Pizza(int diameter, double costPerArea) {
if (diameter <= 0) throw new IllegalArgumentException("diameter must be positive");
if (costPerArea <= 0) throw new IllegalArgumentException("cost per area must be positive");
this.diameter = diameter;
this.costPerArea = costPerArea;
this.price = this.costPerArea*this.calculateArea();
}
public double getPrice() {
return price;
}
private double calculateArea() {
return Math.PI*this.diameter*this.diameter/4.0;
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Pizza{");
sb.append("diameter=").append(diameter);
sb.append(", costPerArea=").append(DEFAULT_FORMAT.format(costPerArea));
sb.append(", price=").append(NumberFormat.getCurrencyInstance().format(getPrice()));
sb.append('}');
return sb.toString();
}
}
For setting a field or another value it is
variable = value;
so
diameter = d;
It looks like your setCost and setDiameter methods need to be changed,
From
d = diameter;
To
this.diameter = d;
Instead of:
System.out.print("The area is: "+this.price);
Use:
System.out.print("The area is: "+this.getPrice());
You need to calculate area as well. So in your main method call it like:
P.calcArea();//to calculate area
You initialised price as 0, when you called new Pizza() and you never called getPrice which is where you calculate the price.
Also change your setter for cost from:
public void setCost(float c) {
c = cost_sq_cm;
}
To
public void setCost(float c) {
cost_sq_cm = c;
}

Can't implement methods in Subclasses from interface

I know this is homework so this may sound weird. Right now I am trying to get rid of a compile error saying pool must implement abstract methods. Pool is implemented by the BackYard interface, while deck is a subclass of pool and bollards is a subclass of deck. I am not allowed to change the code in the display output method in the driver class and I am not allowed to change code in deck or bollards. The compiler keeps insisting that I recode all the subclass methods in pool or make pool abstract which I can't do either. What exactly do I need to fix. Also let me know if I really needed to code all the get methods in the Backyard interface
Here is the driver class:
public class YardOrders
{
//Constants
final static int POOL_ONLY = 1;
final static int POOL_N_DECK=2;
final static int POOL_DECK_N_BOLLARD=3;
final static int DISPLAY_ORDERS=4;
final static int DEFAULT_INT=0;
//Methods
public static void main(String[] args)
{
int numberOfOrders=DEFAULT_INT;
BackYard backYard[] = new BackYard[100];
int selection = DEFAULT_INT;
do
{
selection = Integer.parseInt(JOptionPane.showInputDialog(null,
"Options:\nEnter "+ POOL_ONLY +" for a pool.\n" +
"Enter "+ POOL_N_DECK +
" for a pool and a concrete " +
"deck surrounding the pool.\n"+
"Enter "+POOL_DECK_N_BOLLARD+" for a pool," +
" deck, and bollards.\n"+
"Enter "+DISPLAY_ORDERS+" to display orders and exit.",
"Pool Options", JOptionPane.PLAIN_MESSAGE));
if(selection > DEFAULT_INT && selection < DISPLAY_ORDERS)
{
getPoolInput(backYard,numberOfOrders,selection);
numberOfOrders++;
System.out.println(numberOfOrders);
}
else if(selection==DISPLAY_ORDERS)
{
displayOrders(backYard,numberOfOrders);
System.out.println(numberOfOrders);
System.exit(DEFAULT_INT);
}
else
{
JOptionPane.showMessageDialog(null,"Invalid input. Values" +
" must be between 1 and 4.");
}
}while(selection != DISPLAY_ORDERS);
}
private static void getPoolInput(BackYard backYard[],int numberOfOrders,int selection)
{
//Pool attributes
String lastName = JOptionPane.showInputDialog(null,
"Enter last name.\n","Last Name",
JOptionPane.PLAIN_MESSAGE);
String firstName = JOptionPane.showInputDialog(null,
"Enter first name.","First Name",
JOptionPane.PLAIN_MESSAGE);
double poolDepth = Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter pool depth in inches.","Pool Depth",
JOptionPane.PLAIN_MESSAGE)); //In inches.
double poolDiameter = Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter pool diameter in feet.","Pool Diameter",
JOptionPane.PLAIN_MESSAGE));//In feet.
if(selection == POOL_ONLY)
{
//Pool instantiation.
backYard[numberOfOrders]= new Pool(lastName,firstName,
poolDepth,poolDiameter);
}
else
{
getDeckInput(backYard,
numberOfOrders,selection,
lastName,firstName,
poolDepth, poolDiameter);
}
}//End of method
private static void getDeckInput(BackYard[] backYard,
int numberOfOrders, int selection,
String lastName, String firstName,
double poolDepth, double poolDiameter)
{
//Deck attributes
double deckLength=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter deck length in feet.","Deck Length",
JOptionPane.PLAIN_MESSAGE));
double deckWidth= Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter deck width in feet.","Deck Width",
JOptionPane.PLAIN_MESSAGE));
if(selection==POOL_N_DECK)
{
backYard[numberOfOrders]= new Deck(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth);
}
else
{
getBollardInput(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth);
}
}
public static void getBollardInput(String lastName, String firstName,
double poolDepth, double poolDiameter,
double deckLength, double deckWidth)
{
//Bollard attributes
double bollardHeight=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter bollard height in inches.","Bollard Height",
JOptionPane.PLAIN_MESSAGE));
double bollardDiameter=Double.parseDouble(
JOptionPane.showInputDialog(null,
"Enter bollard diameter in incehs.","Bollard Diameter",
JOptionPane.PLAIN_MESSAGE));
int numberOfBollards=Integer.parseInt(
JOptionPane.showInputDialog(null,
"Enter the number of bollards.","Number of bollards",
JOptionPane.PLAIN_MESSAGE));
//Bollard instantiation
Bollards bollards= new Bollards(lastName,firstName,
poolDepth,poolDiameter,
deckLength,deckWidth,
bollardHeight, bollardDiameter,
numberOfBollards);
}
private static void displayOrders(BackYard[] orders, int numberOfOrders)
{
DecimalFormat dec3 = new DecimalFormat("0.000");
String divider = "******************************************************" +
"***********\n";
JTextArea textOut = new JTextArea(divider, 10, 30);
JScrollPane scroller = new JScrollPane(textOut);
for(int sub = 0; sub < numberOfOrders; sub++)
{
textOut.append("Customer Name: " + orders[sub].getLastName() + ", ");
textOut.append(orders[sub].getFirstName() + "\n");
textOut.append("Pool Depth:" +
dec3.format(orders[sub].getInsideDepth()) + "\n");
textOut.append("Pool Diameter: "+
dec3.format(orders[sub].getInsideDiameter()) + "\n");
textOut.append("Deck Width: " +
dec3.format(orders[sub].getDeckWidth()) + "\n");
textOut.append("Deck Length: " +
dec3.format(orders[sub].getDeckLength()) + "\n");
textOut.append("Number of Bollards Ordered: " +
orders[sub].getNumberOfBollards() + "\n");
textOut.append("Height of Bollards: " +
dec3.format(orders[sub].getBollardHeight()) + "\n");
textOut.append("Diameter of Bollards: " +
dec3.format(orders[sub].getBollardDiameter()) + "\n");
textOut.append("Cubic Yards of Concrete Needed: " +
dec3.format(orders[sub].getConcreteVolume()) + "\n");
textOut.append(divider);
} // end for loop
JOptionPane.showMessageDialog(null, scroller, "Orders Placed",
JOptionPane.PLAIN_MESSAGE);
} // end method DisplayOrders*/
}
Here is the BackYard interface:
public interface BackYard
{
//Universal constants
public static final int CU_IN_TO_CU_YD = 46656;
public static final int FT_TO_IN = 12;
public static final double DENSITY = 3.75; // in inches
//Pool constants.
public static final String DEFAULT_NAME = "Unknown";
public static final int DEFAULT_DIAM_DEPTH = 0;
public static final int STANDARD_DEPTH = 24; // in inches
public static final int STANDARD_DIAMETER = 6; // in feet
public static final int MIN_DEPTH = 10; // in inches
public static final int MAX_DEPTH = 72; // in inches
public static final int MIN_DIAMETER = 3; // in feet
public static final int MAX_DIAMETER = 25; // in feet
//Deck constants
public final static double MAX_DECK_LENGTH = 50.0; // in feet
public static final double MAX_DECK_WIDTH = 50.0; // in feet
public static final int DEFAULT_WIDTH_AND_LENGTH = 0;
//Bollard constants
public static final double MAX_BOLLARD_HEIGHT = 60.0; // in inches
public static final double MIN_BOLLARD_HEIGHT = 24.0; // in inches
public static final double MAX_BOLLARD_DIAMETER = 18.0; // in inches
public static final double MIN_BOLLARD_DIAMETER = 3.0; // in inches
public static final int MIN_NUMBER_OF_BOLLARDS = 4; // units
//Methods.
public abstract String getLastName();
public abstract String getFirstName();
public abstract double getInsideDepth();
public abstract double getInsideDiameter();
public abstract double getDeckWidth();
public abstract double getDeckLength();
public abstract int getNumberOfBollards();
public abstract double getBollardHeight();
public abstract double getBollardDiameter();
public abstract double getConcreteVolume();
}
Here is the pool class
public class Pool implements BackYard
{
// instance variable(s)
private double insideDiameter; // in feet
private double insideDepth; // in inches
private String lastName;
private String firstName;
// class variable(s)
public static int numberOfOrders;
// Zero argument constructor. Sets instance variables to default values
public Pool()
{
setInsideDiameter(DEFAULT_DIAM_DEPTH);
setInsideDepth(DEFAULT_DIAM_DEPTH);
setLastName(DEFAULT_NAME);
setFirstName(DEFAULT_NAME);
}
// Two parameter constructor.
// Sets names to input values and measurements to standard values
public Pool(String lastNameIn, String firstNameIn)
{
setInsideDiameter(STANDARD_DIAMETER);
setInsideDepth(STANDARD_DEPTH);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// Three parameter constructor.
// Sets names and depth to input values and diameter to standard value
public Pool(String lastNameIn, String firstNameIn, double depthIn)
{
setInsideDiameter(STANDARD_DIAMETER);
setInsideDepth(depthIn);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// Three parameter constructor.
// Sets all instance variables to input values
public Pool(String lastNameIn, String firstNameIn, double depthIn,
double diameterIn)
{
setInsideDiameter(diameterIn);
setInsideDepth(depthIn);
setLastName(lastNameIn);
setFirstName(firstNameIn);
numberOfOrders++;
}
// returns depth
public double getInsideDepth()
{
return insideDepth;
}
// validates input and sets depth
public void setInsideDepth(double inDepth)
{
insideDepth = ((inDepth >= MIN_DEPTH &&
inDepth <= MAX_DEPTH) ? inDepth : DEFAULT_DIAM_DEPTH);
}
// returns diameter
public double getInsideDiameter()
{
return insideDiameter;
}
// validates diameter and sets diameter
public void setInsideDiameter(double inDiameter)
{
insideDiameter = ((inDiameter >= MIN_DIAMETER &&
inDiameter <= MAX_DIAMETER) ? inDiameter : DEFAULT_DIAM_DEPTH);
}
// validates and sets last name
public void setLastName(String lastNameIn)
{
lastName = ((lastNameIn.length()) > 0 ? lastNameIn : DEFAULT_NAME);
}
// returns last name
public String getLastName()
{
return lastName;
}
// validates and sets first name
public void setFirstName(String firstNameIn)
{
firstName = ((firstNameIn.length()) > 0 ? firstNameIn : DEFAULT_NAME);
}
// returns first name
public String getFirstName()
{
return firstName;
}
// calculates total concrete necessary in cubic yards and returns that value
#Override
public double getConcreteVolume()
{
if(getInsideDiameter() == 0 || getInsideDepth() == 0)
return 0.000;
else
return (getCylinderVolume(getInsideDiameter() * FT_TO_IN + DENSITY +
DENSITY, getInsideDepth() + DENSITY) / CU_IN_TO_CU_YD) -
(getCylinderVolume(getInsideDiameter() * FT_TO_IN,
getInsideDepth())) / CU_IN_TO_CU_YD;
}
// private utility method used to calculate the volume of a cylinder
public double getCylinderVolume(double diameter, double height)
{
return (Math.PI * Math.pow(diameter / 2.0, 2)) * height;
}
} //end class Pool
Ever signed a contract before?
This code:
public class Pool implements BackYard
is just like one. It's like Pool saying to Backyard: "Hey Backyard, I'm signing a contract that guarantees I'll create code for all the methods you have."
But Pool violated the contract.
The police (compiler) finds out about it and says: Do it buddy or make your kids do it.
Either you fullfil the contract yourself (i.e. create code for all methods mentioned in Backyard) or let your descendants be the ones to complete it (the subclasses will be the ones to add code). You're kind of "punished" - keeping you in an abstract state until the commitment is completed.
First concrete class must implement all abstract methods from its supertypes. In your case you either make Pool abstract, all implement all abstract methods from supertypes that are not already implemented.
In other words, If you allowed not abstract class Pool to have abstract methods, then client of your library could do
Pool p = new Pool();
p.getBollardHeight();
which cannot work, because this method is not implemented. If, on the other hand, you made Pool abstract, you would not be allowed to instantiate it and the problem above would not occur.
You must create all the methods you see in BackYard, inside the Pool class

Categories

Resources