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
Related
This question already has answers here:
Java error: constructor in class cannot be applied to given types
(3 answers)
Closed 4 years ago.
I have a three classes, one to demo and another to extend the first. Everything compiles when in the demo is gives me this error:
EssayDemo.java:11: error: constructor Essay in class Essay cannot be applied to given types;
Essay termPaper = new Essay();
^
required: int,int,int,int
The four ints are Grammar, Spelling, Length, and Content. I set them up but they don't construct an object properly.
This might have been easier if it weren't for the fact that I have to use two classes that I didn't write. Here are the two specific pieces of code. Here's the essayDemo.java:
/**
This program demonstrates a solution to
the Essay Class programming challenge.
*/
public class EssayDemo
{
public static void main(String[] args)
{
// Create an Essay object.
Essay termPaper = new Essay();
// Assign scores to the object.
// Grammer = 25 points, Spelling = 18 points,
// Length = 20 points, and Content = 25 points.
termPaper.setScore(25.0, 18.0, 20.0, 25.0);
// Display the score details.
System.out.println("Term paper:");
System.out.println("Grammar points: " + termPaper.getGrammar());
System.out.println("Spelling points: " + termPaper.getSpelling());
System.out.println("Length points: " + termPaper.getCorrectLength());
System.out.println("Content points: " + termPaper.getContent());
System.out.println("Total points: " + termPaper.getScore());
System.out.println("Grade: " + termPaper.getGrade());
}
}
And here's the gradedActivity.java:
/**
The GradedActivity class stores data about a graded
activity for the Essay Class programming challenge.
*/
public class GradedActivity
{
private double score; // Numeric score
/**
The setScore method sets the score field.
#param s The value to store in score.
*/
public void setScore(double s)
{
score = s;
}
/**
The getScore method returns the score.
#return The value stored in the score field.
*/
public double getScore()
{
return score;
}
/**
The getGrade method returns a letter grade
determined from the score field.
#return The letter grade.
*/
public char getGrade()
{
char letterGrade;
if (score >= 90)
letterGrade = 'A';
else if (score >= 80)
letterGrade = 'B';
else if (score >= 70)
letterGrade = 'C';
else if (score >= 60)
letterGrade = 'D';
else
letterGrade = 'F';
return letterGrade;
}
}
Here's the code I've written to extend it:
public class Essay extends GradedActivity
{
private final int grammarPossible = 30;
private final int spellingPossible = 20;
private final int lengthPossible = 20;
private final int contentPossible = 30;
private final int overallPossible = 100;
private int grammarGrade;
private int spellingGrade;
private int lengthGrade;
private int contentGrade;
private int overallGrade;
public Essay(int grammar, int spelling, int length, int content){
setGrammarGrade(grammar);
setSpellingGrade(spelling);
setLengthGrade(length);
setContentGrade(content);
setOverallGrade();
setScore(getOverallGrade());
}
public int getGrammarGrade(){
return grammarGrade;
}
public void setGrammarGrade(int grammarGrade){
this.grammarGrade = grammarGrade;
}
public int getSpellingGrade(){
return spellingGrade;
}
public void setSpellingGrade(int spellingGrade){
this.spellingGrade = spellingGrade;
}
public int getLengthGrade(){
return lengthGrade;
}
public void setLengthGrade(int lengthGrade){
this.lengthGrade = lengthGrade;
}
public int getContentGrade(){
return contentGrade;
}
public void setContentGrade(int contentGrade){
this.contentGrade = contentGrade;
}
public int getOverallGrade(){
return overallGrade;
}
public void setOverallGrade(){
int grades = grammarGrade + spellingGrade + lengthGrade + contentGrade;
this.overallGrade = grades;
}
public int getGrammarPossible(){
return grammarPossible;
}
public int getSpellingPossible(){
return spellingPossible;
}
public int getLengthPossible(){
return lengthPossible;
}
public int getContentPossible(){
return contentPossible;
}
public int getOverallPossible(){
return overallPossible;
}
}
I have four ints in the essay method but they aren't excepted in the constructor. Everything compiles.
required: int,int,int,int
The error is telling you that your constructor requires arguments (public Essay(int grammar, int spelling, int length, int content)). Right now you are trying to construct an Essay , but are not passing any arguments to it.
You need to provide those arguments, or provide a no args constructor:
public Essay(){}
Or if you wanted to initialize them all to zero and initialize the variables later:
Essay termPaper = new Essay(0,0,0,0);
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
}
}
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 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
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.