In the 2 similar methods with measure in their name, they output the data that I want to have output in the last method many times. But if I try to simply call them in the last method the message does not work anymore. I also have another class with a main method where I create an object that calls the last method as many times as needed. Here is the code.
public class Weatherstation{
double temperature;
double windspeed;
double windChillTemperature;
double actualTemperature;
double actualSpeed;
public void measureTemperature(){
for (temperature = -10; temperature <= 30; temperature = temperature + 5)
{
System.out.println(temperature);
if(temperature == 30)
while(temperature > -10)
{
System.out.println(temperature-1);
temperature = temperature - 1;
}
}
}
public void measureWindspeed(){
for (windspeed = 0; windspeed <= 80; windspeed = windspeed + 8)
{
System.out.println(windspeed);
if(windspeed == 80)
while(windspeed > 0)
{
System.out.println(windspeed-16);
windspeed = windspeed-16;
}
}
}
public void calculateWindChillTemperature(){
windChillTemperature = 13.12 + (0.6215 * temperature) + ((0.3965 * temperature) - 11.37) * Math.pow(windspeed, 0.16);
}
public void generateWeatherMessage(){
String warning="";
calculateWindChillTemperature();
if(windspeed >= 70)
warning += "Wind Warning";
if(windChillTemperature >= -18)
warning += "Cold Warning";
System.out.println("Actual weather: Temp: "+temperature+"°C (Wind: "+windspeed+"km/h) Chilltemp: "+windChillTemperature+"°C, "+warning);
}
}
public class WeatherstationTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Weatherstation w1 = new Weatherstation();
for(int i = 0; i <= 10; i++)
w1.generateWeatherMessage();
}
}
You're not passing any information into Weatherstation to calculate, so all the variables are zero.
Add a constructor like so:
public Weatherstation(double temperature, double windspeed, double windChillTemperature, double actualTemperature, double actualSpeed) {
this.temperature = temperature;
this.windspeed = windspeed;
this.windChillTemperature = windChillTemperature;
this.actualTemperature = actualTemperature;
this.actualSpeed = actualSpeed;
}
Then modify your test class to pass in the variables:
public class WeatherstationTester {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
Weatherstation w1 = new Weatherstation(i, i, i, i, i);
w1.generateWeatherMessage();
}
}
}
public enum Operator {
PLUS("+"),
MINUS("-");
private final String operator;
Operator(String operator) {
this.operator = operator;
}
public String getOperator() {
return operator;
}
public static Operator getByValue(String operator) {
for (Operator operatorEnum : Operator.values()) {
if (operatorEnum.getOperator().equals(operator)) {
return operatorEnum;
}
}
throw new IllegalArgumentException("Invalid value");
}
}
//////////
public enum MetricConvertor {
m(1000),
cm(10),
mm(1),
km(1000000),
dm(100);
private int scale;
MetricConvertor(int scale) {
this.scale = scale;
}
public int getScale() {
return scale;
}
}
/////////
public class Application {
public static void main(String[] args) {
int scale = MetricConvertor.valueOf("m").getScale();
}
I wan to create a calculator that is capable of computing a metric distance value from an expression that contains different scales and systems.
Output should be specified by the user.
Only Addition and subtraction is allowed.
Output is in lowest unit.
Expression: 10 cm + 1 m - 10 mm
Result: 1090 mm
I am stuck at this point, how can I add or substract the values for a list and convert them at the lowest scale sistem( eg above mm, but it can be dm if are added for example dm + m + km)
Here is solution
split each string by add/minus and add it to appropriate list
split number and metric in each list(can use matcher) and sum it
result = sumAdd - sumMinus(mm).
Please optimize it, because i don't have time to optimize this code, I need to go to bed :D
Result is in mm, so you have to get lowest metric and recaculate it(leave it to you).
private static int caculator(String exp) {
List<String> addList = new ArrayList<>();
List<String> minusList = new ArrayList<>();
int checkPoint = 0;
boolean op = true;//default first value is plus
// Split string with add/minus
for (int i = 1; i < exp.length(); i++) {
String s = exp.substring(i, i + 1);
if (Operator.PLUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = true;
continue;
}
if (Operator.MINUS.getOperator().equals(s)) {
checkOperator(addList, minusList, op, exp.substring(checkPoint, i).trim());
checkPoint = i + 1;
op = false;
continue;
}
}
// Add last string
checkOperator(addList, minusList, op, exp.substring(checkPoint).trim());
// Get sum each list
int sumAdd = sumList(addList);
int sumMinus = sumList(minusList);
return sumAdd - sumMinus;
}
//sum a list
private static int sumList(List<String> addList) {
int sum = 0;
for (String s: addList) {
String[] arr = s.split(" ");
int value = Integer.parseInt(arr[0]);
int scale = MetricConvertor.valueOf(arr[1]).getScale();
sum += value * scale;
}
return sum;
}
// check operator to put into approriate list
private static void checkOperator(List<String> addList, List<String> minusList, boolean op, String substring) {
if (op) {
addList.add(substring);
} else {
minusList.add(substring);
}
}
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 anybody help me with this?
simple pizza order program
I tried to run it in commandpromt and there are a lot of error
I have tried to change the double into int.. but the result is still error
<pre>
public class PizzaOrder
{
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEIDUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args command-line arguments
*/
public static int getDiameter(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return SMALL_DIAMETER;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return MEDIUM_DIAMETER;
}`enter code here`
else if (pizzaName.equals(PIZZA_LARGE))
{
return LARGE_DIAMETER;
}
else
{
return COLOSSAL_DIAMETER;
}
}
public static int getBasePrice(String pizzaName)
{
if (pizzaName.equals(PIZZA_SMALL))
{
return PRICE_SMALL;
}
else if (pizzaName.equals(PIZZA_MEIDUM))
{
return PRICE_MEDIUM;
}
else if (pizzaName.equals(PIZZA_LARGE))
{
return PRICE_LARGE;
}
else
{
return PRICE_COLOSSAL;
}
}
there are error about the scanner too idk why
there are 13-20 errors and mostly because of the variables PIZZA_SMALL, etc
some errors say "incompetible types" and the other says "cannot find symbol"
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you"
+ "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,
1).toUppercase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEIDUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLOSSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
else
{
pizzaTopping = pizzaTopping;
}
int radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
Your PizzaOrder class should be as follows:
public class PizzaOrder {
public static final String PIZZA_SMALL = "S";
public static final String PIZZA_MEDIUM = "M";
public static final String PIZZA_LARGE = "L";
public static final String PIZZA_COLLOSAL = "C";
public static final double SMALL_DIAMETER = 9;
public static final double MEDIUM_DIAMETER = 13;
public static final double LARGE_DIAMETER = 17;
public static final double COLOSSAL_DIAMETER = 26;
public static final double PRICE_SMALL = 8;
public static final double PRICE_MEDIUM = 11;
public static final double PRICE_LARGE = 15;
public static final double PRICE_COLOSSAL = 21;
public static final double PRICE_TAX = 0.095;
public static final double PRICE_TOPPING = 0.99;
public static final int MAX_TOPPINGS = 8;
public static final int MIN_TOPPINGS = 0;
/**
* Pizza Order
*
* #param args
* command-line arguments
*/
public static double getDiameter(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return SMALL_DIAMETER;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return MEDIUM_DIAMETER;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return LARGE_DIAMETER;
} else {
return COLOSSAL_DIAMETER;
}
}
public static double getBasePrice(String pizzaName) {
if (pizzaName.equals(PIZZA_SMALL)) {
return PRICE_SMALL;
} else if (pizzaName.equals(PIZZA_MEDIUM)) {
return PRICE_MEDIUM;
} else if (pizzaName.equals(PIZZA_LARGE)) {
return PRICE_LARGE;
} else {
return PRICE_COLOSSAL;
}
}
}
Notice how I corrected the return type from int to double on getDiameter and getBasePrice, as the constants you are trying to return are double. I also fixed the misspelling of "Medium" in some places.
To fix the scanner error, you must import it's package using: (Add this at the top of the file)
import java.util.Scanner;
You main method should look like this: (Again, misspelling variables and casting errors)
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter The Size of Pizza you" + "want: (S/M/L/C)");
String option = keyboard.nextLine().trim().substring(0,1).toUpperCase();
double pizzaPrice;
double pizzaSize;
if(option.equals(PIZZA_SMALL))
{
pizzaPrice = SMALL_DIAMETER;
pizzaSize = SMALL_DIAMETER;
}
else if (option.equals(PIZZA_MEDIUM))
{
pizzaPrice = PRICE_MEDIUM;
pizzaSize = MEDIUM_DIAMETER;
}
else if (option.equals(PIZZA_LARGE))
{
pizzaPrice = PRICE_LARGE;
pizzaSize = LARGE_DIAMETER;
}
else
{
option = PIZZA_COLLOSAL;
pizzaPrice = PRICE_COLOSSAL;
pizzaSize = COLOSSAL_DIAMETER;
}
System.out.println("Pizza Size: " + option);
System.out.println("Enter The Number of Toppings" +
"you want:(0-8)");
int pizzaTopping = keyboard.nextInt();
if(pizzaTopping < MIN_TOPPINGS)
{
pizzaTopping = MIN_TOPPINGS;
}
else if(pizzaTopping > MAX_TOPPINGS)
{
pizzaTopping = MAX_TOPPINGS;
}
double radius = getDiameter(option) / 2;
double squareInches = radius * radius * Math.PI;
System.out.println("Pizza Size: " + option + "( " + pizzaSize +
"inch -- " + squareInches + " square inches)" );
System.out.println("Toppings: " + pizzaTopping);
double priceWithToppings = getBasePrice(option) + pizzaTopping * 9;
System.out.println("Price: " + priceWithToppings);
double pizzaTax = priceWithToppings * PRICE_TAX;
System.out.println("Tax: "+ pizzaTax);
double totalPrice = priceWithToppings + pizzaTax;
System.out.println("Total Price: " + totalPrice);
double priceEachSquareInch = priceWithToppings / squareInches;
System.out.println("Price/sq.in.: " + priceEachSquareInch);
}
}
If you want to cast a double to an int, you need to do int something = (int)myDouble. Also pay attention when writing your variable names, as they must be exactly the same as the definition or they will throw an error. Also, if a method returns an int, but you try and return a double, it will result in an error, as the return type must be the same as what is defined in the method.
Firstly, take a good look through your code as many of your errors are typos - e.g. toUppercase(), COLLOSAL etc.
And, as per Ben's comment you are using doubles for your constants but then your methods are all integers. Java won't let you do this automatically as it results everything after the decimal point being lost as integers are whole numbers only.
When these two things are changed your code appears to work - at a quick glimpse at least.
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