How do i avoid using if-else in this code? - java

As part of my learning process, I am creating a small program in Java that would help a fictitious company help in selling burgers.
In the code below, I created class for a burger and added options to add additions to that burger (like lettuce, carrots etc).
The problem I am facing is how to go about checking each extra addition to the base hamburger (base hamburger meaning only bun and meat) without using if-else too much. One way I tried (you can also see that in code) is by assigning each addition a number, for example, 1 to lettuce, 2 carrots and so on. By adding 1 and 2 we get 3; we can look for 3 to find whether lettuce and carrot are added so that we can calculate price. I did this with other options too.
Some problems arose, however:
There are some cases when a number generated by adding is created twice from different additions this can be tackled somewhat by multiplying the number with some number or by adding 1 as I create more edge cases.
My main problem, by creating such cases, is that it would require a lot of if-else statements, which I am trying to avoid in order to effectively code what i need.
Please suggest if there is any other way to do it. Please note code is not yet complete since I didn't want to create more if-else statements (in hamburger class; method cal_price) to check for additions, but it is enough to fully understand the nature of code. Code is given below:
public class Main {
public static void main(String[] args) {
Breadroll breadroll_type = new Breadroll("Sesame Seed Bun");
meat meat_type = new meat("Beef");
Hamburger my_burger = new Hamburger("Hamburger",breadroll_type,meat_type);
my_burger.select_items(1,2,3,4);
my_burger.cal_price();
my_burger.getBreadroll_type();
my_burger.getMeat_type();
}
}
public class Breadroll {
private String breadroll_type;
public Breadroll(String breadroll_type) {
this.breadroll_type = breadroll_type;
}
public String getBreadroll_type() {
return breadroll_type;
}
}
public class meat {
private String meat_type;
public meat(String meat_type) {
this.meat_type = meat_type;
}
public String getMeat_type() {
return meat_type;
}
}
public class Hamburger {
private String name;
Breadroll breadroll_type;
meat meat_type;
private double base_price; //Price without addons
private int lettuce;
private int carrot;
private int tomato;
private int cheese;
private int hot_sauce;
private int mustard;
private int total_select;
public Hamburger(String name, Breadroll breadroll_type, meat meat_type) {
this.name = name;
this.breadroll_type = breadroll_type;
this.meat_type = meat_type;
this.base_price = 2.75;
}
public void select_items(int lettuce, int carrot, int tomato, int cheese) {
this.lettuce = lettuce;
this.carrot = carrot;
this.tomato = tomato;
this.cheese = cheese;
this.total_select = lettuce + carrot + tomato + cheese;
}
public void cal_price()
{
double final_price;
double lettuce_price = 0.50;
double carrots_price = 0.60;
double tomatos_price = 0.70;
double cheese_price = 0.85;
if(total_select == 0) {
System.out.println("Order Placed : Hamburger with no additions " + getBase_price() + "$");
}
else if (total_select == 1) {
final_price = getBase_price() + lettuce_price;
System.out.println("Order Placed : Hamburger with all lettuce " + (float) final_price + "$");
}
else if (total_select == 2) {
final_price = getBase_price() + carrots_price;
System.out.println("Order Placed : Hamburger with all carrot " + (float) final_price + "$");
}
else if (total_select == 3) {
final_price = getBase_price() + tomatos_price;
System.out.println("Order Placed : Hamburger with all tomato " + (float) final_price + "$");
}
else if (total_select == 4) {
final_price = getBase_price() +cheese_price;
System.out.println("Order Placed : Hamburger with all cheese " + (float) final_price + "$");
}
else if (total_select*100 == 1000) {
final_price = getBase_price() + lettuce_price + carrots_price + tomatos_price + cheese_price;
System.out.println("Order Placed : Hamburger with all additions " + (float) final_price + "$");
}
}
public String getName() {
return name;
}
public void getBreadroll_type() {
System.out.println(breadroll_type.getBreadroll_type());
}
public void getMeat_type() {
System.out.println(meat_type.getMeat_type());
}
public double getBase_price() {
return base_price;
}
public int getLettuce() {
return lettuce;
}
public int getCarrot() {
return carrot;
}
public int getTomato() {
return tomato;
}
public int getCheese() {
return cheese;
}
}

Your implementation of a ‘hamburger’ object seems to be a bit over-complicated. Usually object oriented programming to represent actual, physical objects should choose the simplest, most atomic attributes as possible to avoid situations like this. A hamburger either does or does not have lettuce. It either does or does not have tomato. My recommendation is to have separate Boolean variables for each topping, or a Boolean array representing the toppings if you’d prefer. Then, add a get_price() method to your Hamburger which has a single block of if statements for calculating your price. If you really want to get into OOP, each topping could be an object with a price, which you append to a Toppings ArrayList on your hamburger. Then, your get_price() method would use a for-each to total all the prices of your Topping objects, as well as your hamburger’s price attribute. This method might be better if you want multiple quantities of the same topping. This is the fun part of programming - you can choose the implementation that makes the most sense to you and try it out!

Made a hamburger with name, breadtype, meattype and added the extra's later on, you can make seperate methods for the breadtype and meat as well. In the extra methods we calculate the extra price beforehand so calling getPrice() sums up all the extras with chosen bread/meat type. There are other ways to do this but this way you'll also have an example of a contract and switch statement. Removed a few ingredients but you get the point.
Also take look at the naming conventions how they are different from yours.
class HamburgerContract {
// Specify your constants in this class so all classes are able to communicate with the same values
// Change the name to something shorter like HBC for easier reference, ie HBC.BR_TYPE_SESAM
public static final int BR_TYPE_SESAM = 1;
public static final int BR_TYPE_HONEY = 2;
public static final int MEAT_TYPE_COW = 1;
public static final int MEAT_TYPE_CHICKEN = 2;
}
public class Hamburger {
public static void main(String[] args) {
// Made a hamburger with name, breadtype, meattype and added the extra's later on
// You can make seperate methods for the breadtype and meat as well
// In the extra methods we calculate the extra price beforehand
// So calling getPrice() sums up all the extras with chosen bread/meat type
// There are other ways to do this but this way you'll also have an example of a contract and switch statement
// Removed a few ingredients but you get the point
Hamburger myHamburger = new Hamburger("Varadero Burger", HamburgerContract.BR_TYPE_SESAM, HamburgerContract.MEAT_TYPE_CHICKEN, 2.50);
myHamburger.addCarrot();
myHamburger.addLettuce();
myHamburger.removeCarrot();
System.out.print("The price of your " + myHamburger.getName() + "is $ " + myHamburger.getPrice());
}
private String burgerName;
private int breadrollType;
private int meatType;
private boolean lettuce;
private boolean carrot;
private double basePrice;
private double extraPrice;
public Hamburger(String burgerName, int breadrollType, int meatType, double basePrice) {
this.burgerName = burgerName;
this.breadrollType = breadrollType;
this.meatType = meatType;
this.basePrice = basePrice;
this.extraPrice = 0;
this.lettuce = false;
this.carrot = false;
}
public void addLettuce() {
// extra check if lettuce is not already added, so you wont add to the price twice
// same goes for removing the lettuce or the carrot methods
if (!lettuce) {
letuce = true;
extraPrice += 0.25;
}
}
public removeLettuce() {
if (lettuce) {
letuce = false;
extraPrice -= 0.25;
}
}
public void addCarrot() {
if (!carrot) {
carrot = true;
extraPrice += 0.20;
}
}
public void removeCarrot() {
if (carrot) {
carrot = false;
extraPrice -= 0.20;
}
}
public String getName() {
return burgerName;
}
public double getPrice() {
switch (breadrollType) {
case HamburgerContract.BR_TYPE_HONEY: extraPrice += 0.25; break;
case HamburgerContract.BR_TYPE_SESAM: extraPrice += 0.50; break;
}
switch (meatType) {
case HamburgerContract.MEAT_TYPE_COW: extraPrice += 0; break;
case HamburgerContract.MEAT_TYPE_CHICKEN: extraPrice += 0.50; break;
}
return basePrice + extraPrice;
}
}

You don't need to use conditional statements at all, just multiply the price of each item by its price:
final_price = getBase_price()
+ lettuce_num * lettuce_price
+ carrots_num * carrots_price
+ tomatos_num * tomatos_price
+ cheese_num * cheese_price;
In your set method you should then set the number/amount of items (e.g., lettuce) and not 1 == lettuce and 2 == xxx :
my_burger.select_items(5,0,0,0); // 5 lettuce, 0 all other
my_burger.select_items(1,0,0,90); // 1 lettuce, 90 cheese, 0 all other
Putting it all together (minified):
public class Main {
public static void main(String[] args) {
Hamburger my_burger = new Hamburger("Hamburger");
my_burger.select_items(
100, // 100 lettuce
0, // 0 carrot
2, // 2 tomato
1); // 1 cheese
my_burger.cal_price();
}
}
public class Hamburger {
private String name;
private double base_price = 2.75;
private int lettuce;
private double lettuce_price = 0.50;
private int carrot;
private double carrots_price = 0.60;
private int tomato;
private double tomatos_price = 0.70;
private int cheese;
private double cheese_price = 0.85;
public Hamburger(String name) {
this.name = name;
}
public void select_items(int lettuce, int carrot, int tomato, int cheese) {
this.lettuce = lettuce;
this.carrot = carrot;
this.tomato = tomato;
this.cheese = cheese;
}
public void cal_price()
{
double final_price = getBase_price()
+ lettuce * lettuce_price
+ carrots * carrots_price
+ tomato * tomatos_price
+ cheese * cheese_price;
// TODO print price
}
}

Related

Trying to change some data types to read a different output other than numbers

I am thinking I need to do some type casting to get the fan to output toString,
to output strings for my speed instead of 1, 2, and 3. I am not sure where I can makes those changes, either being sent in the test class or moving to private in the fan class. I have tried to add some calls in the toString but I am getting the hex decimal result. Some different ways to come around this would be really helpful.
public class Fan {
public final int SLOW = 1;
public final int MEDIUM = 2;
public final int FAST = 3;
private int speed; // = SLOW;
private boolean on; // on = false;
private double radius; // radius = 5;
private String color; // = "white";
public int getSpeed ( ) {return speed; }
public void setSpeed ( int speed ) { this.speed = speed; }
public boolean isOn ( ) {return on; }
public void setOn ( boolean on) {this.on = on; }
public double getRadius ( ) {return radius; }
public void setRadius ( double radius ) { this.radius = radius; }
public String getColor ( ) { return color; }
public void setColor ( String color ) { this.color = color; }
public Fan ( ) {
System.out.println("Default constructor called");
}
// default constructor
public Fan ( int speed, boolean on, double radius, String color ) {
this.speed = speed;
this.on = on;
this.radius = radius;
this.color = color;
System.out.println("Overloaded constructor called");
}
//overloaded constructor
public String toString () {
String x = "speed is " + speed + ", is the fan turned on? " + on + ",the radius "
+ "of the blades are " + radius + ", and the color of the fan is " + color;
return x;
}
}
public class FanTest {
public static void main(String[] args) {
Fan f1 = new Fan( 3, true, 10, "Yellow" ) ;
Fan f2 = new Fan();
Fan f4 = new Fan();
f1.equals(f4) ;
Fan f3 = f1;
int slow = 1;
int medium = 2;
int fast = 3;
System.out.println(f1);
System.out.println(f2);
System.out.println(f3);
if (f1.equals(f3)) {
System.out.println("Obejects r3 and r1 are the same\n");
} else {
System.out.println("Objects r3 and r1 are different");
}
while (f1.equals(f4))
f4.setOn(false);
f4.setSpeed(2);
f4.setColor("green");
f4.setRadius(8);
System.out.println(f4);
}
}
First, in the default constructor no variables are set. This means that any Fan object created with the default constructor is in an invalid state (e.g. speed is 0 by default). I suggest you to uncomment line 9-12:
private int speed = SLOW;
private boolean on = false;
private double radius = 5;
private String color = "white";
You said you wanted to "output strings for my speed instead of 1, 2, and 3". This can easily be achieved using if..else or switch.
if (speed == 1) {
str = str + " slow ";
} else if (speed == 2) {
str = str + " medium ";
} else if (speed == 3) {
str = str + " fast ";
}
Using switch:
switch (speed) {
case 1:
str = str + " slow ";
break;
case 2:
str = str + " medium ";
break;
case 3:
str = str + " fast ";
break;
}
About f1.equals(f4): These are different objects, so it is never true.
About equals: equals is a method defined in the class Object, so it can be used on any object. But unless you override it, it checks for identity, witch means that
a.equals(b)
always returns the same as
a == b

Converting the same String value into an Object

I have an object share:
Share tea = new Share("TEA", "Common", 0, 100);
ArrayList<Share> shares = new ArrayList<Share>();
shares.add(tea);
What I'd like to do is, reading parameters from the keybord, convert directly the "tea" string into a share tea object :
Trade trade = new Trade( tea, Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
What should I put instead of tea because my constructor is waiting a Share and not a String. The user is entering a string and I don't need ton create a new instance, I have to use the Share object "tea" that already exists.
The Share.java class :
public class Share {
private String shareSymbol = "";
private String type = "Common";
private double lastDividend = 0;
private double fixedDividend = 0;
private int parValue = 0;
// Calucul values
public String getShareSymbol() {
return shareSymbol;
}
public String getType() {
return type;
}
public double getLastDividend() {
return lastDividend;
}
public double getFixedDividend() {
return fixedDividend;
}
public int getParValue() {
return parValue;
}
// Constructor without Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend, int parValue) {
this.shareSymbol = shareSymbol;
this.type = type;
this.lastDividend = lastDividend;
this.parValue = parValue;
}
// Constructor with Fixed Dividend
public Share(String shareSymbol, String type, int lastDividend,
int fixedDividend, int parValue) {
this(shareSymbol, type, lastDividend, parValue);
this.fixedDividend = fixedDividend / 100.0;
}
public String toString(){
String result="";
result += shareSymbol + " "+type + " " + lastDividend + " " + fixedDividend + " " + parValue + "\n";
return result;
}
}
The Trade.java class :
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
// The class trade allows the stock, the quantity and the price to be intialised
public class Trade {
Share share;
private int quantity;
double price;
private double dividendYield;
private double pERatio;
private boolean buyOrSell;
private Date tradeDate;
public Trade(Share share, boolean buyOrSell, int quantity, double price) {
this.share = share;
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
}
public String toString() {
String result = "";
result += "stock symbol : " + share.getShareSymbol() + " \n";
result += "Buy or Sell : " + buyOrSell + " \n";
result += "quantity :" + quantity + " \n";
result += "price : " + price + " \n";
result += "Dividend Yield : " + dividendYield + " \n";
result += "P/E Ratio : " + pERatio + " \n";
result += "tradeDate : " + tradeDate + " \n\n";
return result;
}
public Share getShare() {
return share;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public double getDividendYield() {
return dividendYield;
}
public double getpERatio() {
return pERatio;
}
public Date getTradeDate() {
return tradeDate;
}
public double calcDividendYield() {
if ("Common".equalsIgnoreCase(share.getType())) {
dividendYield = share.getLastDividend() / price;
} else if ("Preferred".equalsIgnoreCase(share.getType())) {
dividendYield = share.getFixedDividend() * share.getParValue()
/ price;
}
return dividendYield;
}
public double calcPERatio() {
if (dividendYield > 0)
pERatio = price / dividendYield;
return pERatio;
}
}
Your constructor is waiting a share. So give it:
/* Read parameters from keyboard, stock in s1, s2, i1 and i2 variables */
Trade trade = new Trade( new Share(s1,s2,i1,i2), Boolean.parseBoolean(buyOrSell), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
Otherwise you can implement a method (in Share class) that do it for you
public static Share stringToShare(String s1, String s2, int t1, int t2){
return new Share(s1, s2, t1, t2);
}
And then:
Trade trade = new Trade( Share.stringToShare(...), Integer.parseInt(quantity), Double.parseDouble(tradePrice));
EDIT: better use real variable names that means something, not s1, s2, etc.
I've got around of this, by creating a new constructor :
Trade trade = new Trade(shares, stockSymbol, Boolean.parseBoolean(buyOrSell),
Integer.parseInt(quantity), Double.parseDouble(tradePrice));
This is then the new constructor :
public Trade(ArrayList<Share> shares, String stockSymbol,
boolean buyOrSell, int quantity, double price) {
Iterator<Share> iter = shares.iterator();
int index = -1;
while (iter.hasNext()) {
Share share = iter.next();
index++;
if (stockSymbol.equalsIgnoreCase((share.getShareSymbol()))) {
this.share = shares.get(index);
this.buyOrSell = buyOrSell;
this.quantity = quantity;
this.price = price;
tradeDate = Calendar.getInstance().getTime();
break;
}
}
}
It's a bit complacated, because I had also to create a new method to get the Share for the given String(having the same name, for instance). But that does What i needed.
It would be cleaner though to make it with Java Reflection, without having to create a new constructor. So if any one have an idea with a code more clever, I would be happy!

Data validation to an throw exception

I am trying to read in a figure for a brokers earnings for quarter one of the year.I want to ensure that 0 or less can not be entered but when I enter 0 it just takes it in anyway and does not throw the exception?
What am I doing wrong?Any help would be greatly appreciated.
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException("new quarter must be > 0.0");
}
Ok heres my whole assignment code
import java.util.Scanner;
public class Broker {
//(a) declare instance variables
private String department, firstName, lastName;
private double quarter1, quarter2, quarter3, quarter4;
//(b) Access methods for instance variables
public void setDepartmentName(String newName)
{
department=newName;
}
public String getDepartment ()
{
return department;
}
//set and get methods for first name
public void setFirstName (String newFirstName)
{
firstName=newFirstName;
}
public String getFirstName ()
{
return firstName;
}
//set and get methods for last name
public void setLastName(String newLastName)
{
lastName=newLastName;
}
public String getLastName ()
{
return lastName;
}
//set and get methods for Quarter 1
public void setQuarter1(double newQuarter1)
{
if ( newQuarter1 > 0)
quarter1 = newQuarter1;
else
throw new IllegalArgumentException(
"new quarter must be > 0.0");
}
public double getQuarter1()
{
return quarter1;
}
//set and get methods for Quarter 2
public void setQuarter2(double newQuarter2)
{
quarter2 = newQuarter2;
}
public double getQuarter2 ()
{
return quarter2;
}
//set and get methods for Quarter 3
public void setQuarter3(double newQuarter3)
{
quarter2 = newQuarter3;
}
public double getQuarter3 ()
{
return quarter3;
}
//set and get methods for Quarter 4
public void setQuarter4(double newQuarter4)
{
quarter4 = newQuarter4;
}
public double getQuarter4 ()
{
return quarter4;
}
//(c) class variable annualbrokerage total and two access methods
private static double brokerageTotal;
public void setbrokerageTotal(double newBrokerageTotal)
{
newBrokerageTotal=brokerageTotal;
}
//(c) constructor to initialise instance variables department,firstname and lastname
public Broker (String dept, String first, String last )
{
department = dept;
firstName = first;
lastName = last;
}
// (d) constructor to initialise all instance variables from (a)
public Broker (String dept, String first, String last,double q1,double q2,double q3,double q4 )
{
department = dept;
firstName = first;
lastName = last;
quarter1 = q1;
quarter2 = q2;
quarter3 = q3;
quarter4 = q4;
}
// (e) no-argument constructor to initialise default broker instance
public Broker ()
{
department = null;
firstName = null;
lastName = null;
quarter1 = 0;
quarter2 = 0;
quarter3 = 0;
quarter4 = 0;
}
//(f) Method to read in quarters from user
public void readInQuarters ()
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt();
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
} //end of read in quarters method
// (g) getBrokerTotal Method to return total trades for 4 quarters
public double getBrokerTotal()
{
//code to calculate broker quarterly totals
double brokerTotal = quarter1 + quarter2 + quarter3 + quarter4;
return brokerTotal;
} //end of getBrokerTotal method
//(e) getBonus method to calculate brokers bonus
public double getBonus()
{
double bonusRate=0;
double bonus=0;
//bonus rate depending on department rate
if("Dublin"==department)
bonusRate=.12;
else if("London"==department)
bonusRate=.15;
else
bonusRate=.10;
bonus = (quarter1 + quarter2 + quarter3 + quarter4)*(bonusRate);
return bonus;
}
//(i) to string method for broker class
public String toString()
{
return String.format(" Name: "+ getFirstName()+"\n Surname: "+getLastName()+"\n Department: "+getDepartment()+"\n Total: "+getBrokerTotal()+"\n Bonus: "+getBonus()+"\n\n");
}//end of toString method
//(i) Static methods to read in broker array and output quarterly totals
//Quarter1 totals method
public static double getQuarter1Total (Broker[]brokerQuarter1Array)
{
double quarter1Total = brokerQuarter1Array[0].getQuarter1()+ brokerQuarter1Array[1].getQuarter1()+ brokerQuarter1Array[2].getQuarter1()+ brokerQuarter1Array[3].getQuarter1()
+ brokerQuarter1Array[4].getQuarter1() + brokerQuarter1Array[5].getQuarter1();
return quarter1Total;
}
//Quarter2 totals method
public static double getQuarter2Total (Broker[]brokerQuarter2Array)
{
double quarter2Total = brokerQuarter2Array[0].getQuarter2()+ brokerQuarter2Array[1].getQuarter2()+ brokerQuarter2Array[2].getQuarter2()+ brokerQuarter2Array[3].getQuarter2()
+ brokerQuarter2Array[4].getQuarter2() + brokerQuarter2Array[5].getQuarter2();
return quarter2Total;
}
//Quarter3 totals method
public static double getQuarter3Total (Broker[]brokerQuarter3Array)
{
double quarter3Total = brokerQuarter3Array[0].getQuarter3()+ brokerQuarter3Array[1].getQuarter3()+ brokerQuarter3Array[2].getQuarter3()+ brokerQuarter3Array[3].getQuarter3()
+ brokerQuarter3Array[4].getQuarter3() + brokerQuarter3Array[5].getQuarter3();
return quarter3Total;
}
//Quarter4 totals method
public static double getQuarter4Total (Broker[]brokerQuarter4Array)
{
double quarter4Total = brokerQuarter4Array[0].getQuarter4()+ brokerQuarter4Array[1].getQuarter4()+ brokerQuarter4Array[2].getQuarter4()+ brokerQuarter4Array[3].getQuarter4()
+ brokerQuarter4Array[4].getQuarter4() + brokerQuarter4Array[5].getQuarter4();
return quarter4Total;
}
// Static method to calculate total brokerage totals for all brokers
public static void setBrokerageTotal (Broker[] brokerTotalsArray)
{
double annualBrokerageTotal= brokerTotalsArray[0].getBrokerTotal() + brokerTotalsArray[1].getBrokerTotal()
+ brokerTotalsArray[2].getBrokerTotal() + brokerTotalsArray[3].getBrokerTotal() + brokerTotalsArray[4].getBrokerTotal() + brokerTotalsArray[5].getBrokerTotal();
}
// Static method to get the total bonuses for all brokers cobined
public static double getBrokerageBonus (Broker [] brokerageBonusTotalArray)
{
double totalBrokerageBonus = brokerageBonusTotalArray[0].getBonus()+ brokerageBonusTotalArray[1].getBonus()+ brokerageBonusTotalArray[2].getBonus()+ brokerageBonusTotalArray[3].getBonus()
+ brokerageBonusTotalArray[4].getBonus() + brokerageBonusTotalArray[5].getBonus();
return totalBrokerageBonus;
}
public static void main(String[]args)
{
//Part-B
///(a) create broker1 with the no argument constructor
Broker broker1=new Broker();
broker1.setDepartmentName("Dublin");
broker1.setFirstName("John");
broker1.setLastName("Wall");
broker1.setQuarter1(12);
broker1.setQuarter2(24);
broker1.setQuarter3(26);
broker1.setQuarter4(17);
System.out.print(broker1);
//(b) create broker2
Broker broker2 = new Broker("London","Sarah","May");
broker2.setQuarter1(8);
broker2.setQuarter2(11);
broker2.setQuarter3(7);
broker2.setQuarter4(9);
System.out.print(broker2);
//(c) create broker3
Broker broker3 = new Broker("London","Ruth","Lavin");
//call read in quarters method
broker3.readInQuarters();
System.out.print(broker3);
//(d) create broker4,broker5,broker6
Broker broker4=new Broker("Dublin","Conor","Smith",21,23,26,31);
Broker broker5=new Broker("Paris","Jerome","Duignan",14,14,17,18);
Broker broker6=new Broker("Paris","Patick","Bateman",23,24,26,35);
//(e) Create broker array
Broker[] brokers;
brokers=new Broker [6];
brokers[0]=broker1;brokers[1]=broker2;brokers[2]=broker3;brokers[3]=broker4;brokers[4]=broker5;brokers[5]=broker6;
//(f) Output second table
String[] headings ={"Dept","Firstname","Surname","Q1","Q2","Q3","Q4","Total","Bonus"};
//loop to print the headings
for (int i = 0; i < headings.length; i++)
{
System.out.print(headings[i]+" ");
}
//print a space under the headings
System.out.println(" \n");
//loop to print the main table plus format specifiers to align the text
for (int i = 0; i < 5; i++)
{
System.out.printf("%-7s %-13s %-11s %-6s %-6s %-6s %-6s %-10s %.1f \n\n",brokers[i].getDepartment(), brokers[i].getFirstName(),brokers[i].getLastName(),brokers[i].getQuarter1(),brokers[i].getQuarter2(),brokers[i].getQuarter3(),brokers[i].getQuarter4(),brokers[i].getBrokerTotal(),brokers[i].getBonus());
}
// console printout for quarterly totals
System.out.printf("%33s \n","Quarterly ");
System.out.printf("%29 %9s %6s %6s %6s %6s \n","Total ",getQuarter1Total(brokers),getQuarter2Total(brokers),getQuarter3Total(brokers),getQuarter4Total(brokers),getBrokerageBonus(brokers));
} //end of method main
} //end of class broker
er
You aren't using your setters. The problem is here
public void readInQuarters () {
Scanner input = new Scanner(System.in);
System.out.println("Please enter Q1,Q2,Q3 and Q4 figures for broker:");
quarter1 = input.nextInt(); // <-- Use your setters!
quarter2 = input.nextInt();
quarter3 = input.nextInt();
quarter4 = input.nextInt();
// should be,
setQuarter1(input.nextInt()); // and so on... although I will point out, you should
// be reading double(s) apparently.
}
Hello Friend I have give a suggestion which is am also use in our project
call this method before submitting the value. And if return true then update data other wise show mgs in validate method of where from call update
boolean validate() {
int c = Integer.parseInt(txtFieldSetupTopElevation.getText().toString().trim());
if (c <= 0) {
// Here use code for show msg error or information
// return true if value is greater than 0 other wise return else
return false;
}
}
Sandeep

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

Not sure what to return from parseStringTo class [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am trying to code a program that can take user input data about a carpet, parse the string into the necessary pieces of information and create carpet objects based off the shape. My code is
public class CarpetParser{
public static Carpet parseStringToCarpet(String lineToParse)
{
String delims = "[/]";
String[] info = lineToParse.split(delims);
if(info[0].equalsIgnoreCase("rectangle")){
double priceFor = Double.parseDouble(info[2]);
int height = Integer.parseInt(info[3]);
int width = Integer.parseInt(info[4]);
RectangleCarpet theCarpet = new RectangleCarpet(info[1], priceFor, height, width);
return theCarpet;
}else if(info[0].equalsIgnoreCase("circle")){
double priceFor = Double.parseDouble(info[2]);
int radius = Integer.parseInt(info[3]);
CircleCarpet theCarpet = new CircleCarpet(info[1], priceFor, radius);
return theCarpet;
}
}
}
for the parser,
public abstract class Carpet{
protected int area = 0;
protected double unitPrice = 0;
protected double totalPrice = 0.0;
protected String carpetID;
public Carpet(String ID, double thisPrice){
carpetID = ID;
unitPrice = thisPrice;
}
public String getCarpetId(){
return carpetID;
}
public String toString(){
String carpet = new String("\n" + "The CarpetId:\t\t" + getCarpetId() + "\nThe Area:\t\t" + area + "\nThe Unit Price\t\t" + unitPrice + "\nThe Total Price\t" + totalPrice + "\n\n");
return carpet;
}
public abstract void computeTotalPrice();
}
for the carpet,
public class RectangleCarpet extends Carpet{
private int height;
private int width;
public RectangleCarpet(String ID, double priceOf, int h, int w){
super(ID, priceOf);
height = h;
width = w;
computeTotalPrice();
}
public void computeTotalPrice(){
super.area = height * width;
super.totalPrice = unitPrice * area;
}
public String toString(){
String forThis = new String("\nThe Carpet Shape:\tRectangle\nThe Height:\t\t" + height + "\nThe Width:\t\t" + width +"\n");
return forThis + super.toString();
}
}
for one of the carpet shapes and
public class CircleCarpet extends Carpet{
private int radius;
public CircleCarpet(String ID, double priceOf, int rad){
super(ID, priceOf);
radius = rad;
computeTotalPrice();
}
public void computeTotalPrice(){
super.area = radius * radius * 3;
super.totalPrice = area * unitPrice;
}
public String toString(){
String forThis = new String("\nThe Carpet Shape:\tCircle\nThe radius:\t\t" + radius + "\n");
return forThis + super.toString();
}
}
for the other shape. The problem is the parseStringToCarpet is missing a return value, and I can't figure out what it needs to return, because if I try to return theCarpet it says it is the wrong type.
The calling class is
`import java.io.*; //to use InputStreamReader and BufferedReader
import java.util.*; //to use ArrayList
public class Menu
{
public static void main (String[] args)
{
char input1;
String inputInfo = new String();
String line = new String();
boolean found;
// ArrayList object is used to store carpet objects
ArrayList carpetList = new ArrayList();
try
{
printMenu(); // print out menu
// create a BufferedReader object to read input from a keyboard
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader stdin = new BufferedReader (isr);
do
{
System.out.println("What action would you like to perform?");
line = stdin.readLine().trim();
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
if (line.length() == 1)
{
switch (input1)
{
case 'A': //Add Carpet
System.out.print("Please enter a carpet information to add:\n");
inputInfo = stdin.readLine().trim();
carpetList.add(CarpetParser.parseStringToCarpet(inputInfo));
break;
case 'C': //Compute Total Price For Each Carpet
for (int i=0; i<carpetList.size();i++)
((Carpet) carpetList.get(i)).computeTotalPrice();
System.out.print("total prices computed\n");
break;
case 'D': //Search for Carpet
System.out.print("Please enter a carpetID to search:\n");
inputInfo = stdin.readLine().trim();
found = false;
for (int i=0; i<carpetList.size();i++)
{
if (inputInfo.equals(((Carpet)carpetList.get(i)).getCarpetId()))
{
found = true;
}
}
if (found == true)
System.out.print("carpet found\n");
else
System.out.print("carpet not found\n");
break;
case 'L': //List Carpets
if (carpetList.isEmpty())
System.out.print("no carpet\n");
else
for (int i=0; i < carpetList.size(); i++)
System.out.print(carpetList.get(i).toString());
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q'); // stop the loop when Q is read
}
catch (IOException exception)
{
System.out.println("IO Exception");
}
}
/** The method printMenu displays the menu to a use **/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Carpet\n" +
"C\t\tCompute Total Price For Each Carpet\n" +
"D\t\tSearch for Carpet\n" +
"L\t\tList Carpets\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
` I'm not allowed to edit the code of the calling class.
You always have to make sure all the paths in a method with returning value have a return in it or throw exception. In this case, you could add:
else {
return null;
}
to the last part of the method parseStringToCarpet, or just write return null at the end of the method.
The problem returning null is that a method that calls this function should know that it might return null, so you should document it.
Return a null object in the end which will be called when if-else condition is not met but make sure you do a not-null check when calling this
public class CarpetParser{
public static Carpet parseStringToCarpet(String lineToParse)
{
String delims = "[/]";
String[] info = lineToParse.split(delims);
if(info[0].equalsIgnoreCase("rectangle")){
double priceFor = Double.parseDouble(info[2]);
int height = Integer.parseInt(info[3]);
int width = Integer.parseInt(info[4]);
RectangleCarpet theCarpet = new RectangleCarpet(info[1], priceFor, height, width);
return theCarpet;
}else if(info[0].equalsIgnoreCase("circle")){
double priceFor = Double.parseDouble(info[2]);
int radius = Integer.parseInt(info[3]);
CircleCarpet theCarpet = new CircleCarpet(info[1], priceFor, radius);
return theCarpet;
}
return null;
}
As you declared the function as returning a Carpet, your class must return a Carpet (even if null).
When info[0] is neither circle or rectangle, your function does not return anything.
A quick fix is to either add a return null; at the end, or throw an exception (i.e. create InvalidArgumentException).
In the second case you must edit the calling class to handle the exception or throw it further up the stack though.

Categories

Resources