Stop method from running twice - java

In the method askCarType() and askSolarPanel() the inputdialog both run two times, once in their own method and once more in the final method PrintOptions().
I need them to only run once, and that is in the final method PrintOptions().
How can I do that?
import javax.swing.*;
public class short7 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PrintOptions();
}// ends main
public static String askCarType() {
String typeOfCar;
typeOfCar = JOptionPane.showInputDialog("Electric or Hybrid?");
if (!typeOfCar.equals("Electric")
&& (!typeOfCar.equals("electric") && (!typeOfCar
.equals("Hybrid") && (!typeOfCar.equals("hybrid"))))) {
JOptionPane
.showMessageDialog(null,
"You have to choose either an Electric or Hybrid type of car.");
typeOfCar = JOptionPane.showInputDialog("Electric or Hybrid?");
}
return typeOfCar;
}// ends askCarType
public static String askSolarPanel() {
String wantSolarPanel;
wantSolarPanel = JOptionPane
.showInputDialog("Do you want a Solar Panel?");
if (!wantSolarPanel.equals("Yes")
&& (!wantSolarPanel.equals("yes") && (!wantSolarPanel
.equals("No") && (!wantSolarPanel.equals("no"))))) {
JOptionPane.showMessageDialog(null,
"You have to enter either Yes or No");
wantSolarPanel = JOptionPane
.showInputDialog("Do you want a Solar Panel?");
}
return wantSolarPanel;
}// ends askSolarPanel
public static int calculateDiscount() {
String typeOfCarSelected = askCarType();
String SolarPanelSelected = askSolarPanel();
int Discount = 0;
if ((typeOfCarSelected.equals("Electric") || typeOfCarSelected
.equals("electric"))
&& ((SolarPanelSelected.equals("Yes") || SolarPanelSelected
.equals("yes")))) {
Discount = 500;
} else {
Discount = 0;
}
return Discount;
}// ends calculateDiscount
public static int CalculateCost() {
String typeOfCarCost = askCarType();
String SolarPanelCost = askSolarPanel();
final int basicPrice = 20000;
final int ElectricModel = 2000;
final int SolarPanel = 5000;
final int Discount = calculateDiscount();
int total = 0;
if ((typeOfCarCost.equals("Electric") || typeOfCarCost
.equals("electric"))
&& ((SolarPanelCost.equals("No") || SolarPanelCost.equals("no")))) {
total = basicPrice + ElectricModel;
System.out.println("Basic Price:" + basicPrice);
System.out.println("Electric Model:" + ElectricModel);
System.out.println("Total:" + total);
} else if ((typeOfCarCost.equals("Electric") || typeOfCarCost
.equals("electric"))
&& ((SolarPanelCost.equals("Yes") || SolarPanelCost
.equals("yes")))) {
total = basicPrice + ElectricModel + SolarPanel - Discount;
System.out.println("Basic Price:" + basicPrice);
System.out.println("Electric Model:" + ElectricModel);
System.out.println("Solar Panel:" + SolarPanel);
System.out.println("Discount:" + Discount);
System.out.println("Total:" + total);
} else {
total += basicPrice;
System.out.println("Basic Price:" + basicPrice);
System.out.println("Total:" + total);
}
return total;
}// ends CalculateCost
public static void PrintOptions() {
CalculateCost();
}// ends PrintOptions
}// ends class short7

you're calling askCarType() and askSolarPanel() twice and what you need is call them one time !, so call them in CalculateCost() and sent the two string typeOfCarCost and SolarPanelCost to the calculateDiscount method like this :
public static int calculateDiscount(String typeOfCarSelected, String SolarPanelSelected) {
int Discount = 0;
if ((typeOfCarSelected.equals("Electric") || typeOfCarSelected.equals("electric")) && ((SolarPanelSelected.equals("Yes") || SolarPanelSelected.equals("yes")))) {
Discount = 500;
} else {
Discount = 0;
}
return Discount;
}//ends calculateDiscount
and in CalculateCost()
public static int CalculateCost() {
String typeOfCarCost = askCarType();
String SolarPanelCost = askSolarPanel();
final int basicPrice = 20000;
final int ElectricModel = 2000;
final int SolarPanel = 5000;
final int Discount = calculateDiscount(typeOfCarCost, SolarPanelCost);/////here you send the input fromthe user to this method without needing to call it again
int total = 0;
....
}

You can declare two class variables.
String typeOfCar;
String wantSolarPanel;
And in askCarType() method assign
typeOfCar = ................
and in askSolarPanel() method assign
wantSolarPanel = .....................
Then use these variables from CalculateCost() and calculateDiscount() rather than calling askCarType() and askSolarPanel() method again.

Related

Java values of toString() not printing

I am new to Java programming. I developed a Pizza class that takes for parameters and outputs the description and cost. I developed a PizzaOrderArray class that stores the pizza orders in an array. I have a class containing the main method also.
When I tried to print the values of the orders, nothing prints yet debugging shows that the proper methods and loops were entered.
What am I doing incorrect? I have invested many hours and am still very confused. Any suggestions, please? Thank you! I appreciate it.
Pizza.java
import java.text.NumberFormat;
import java.util.Locale;
public class Pizza {
public Pizza(String size, int numCheeseTop, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
setNumCheese(numCheeseTop);
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numPepTop, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
setNumPep(numPepTop);
setNumHam(numHamTop);
}
public Pizza(String size, int numHamTop) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_pep = 0;
setNumHam(numHamTop);
pizza_cheese = 0;
}
public Pizza(String size) {
if (!setPizzaSize(size)) {
System.out.println(size + " is invalid size." + "Use small, medium or large.");
}
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza() {
pizza_size = "small";
pizza_cheese = 0;
pizza_pep = 0;
pizza_ham = 0;
}
public Pizza(Pizza copyPizza) {
pizza_size = copyPizza.getPizzaSize();
pizza_cheese = copyPizza.getNumCheese();
pizza_pep = copyPizza.getNumPep();
pizza_ham = copyPizza.getNumHam();
}
//Setters
public boolean setPizzaSize(String size) {
if (size.equalsIgnoreCase("small") || (size.equalsIgnoreCase("medium") || (size.equalsIgnoreCase("large")))) {
pizza_size = size.toLowerCase();
return true;
}
return false;
}
public void setNumCheese(int numCheeseTop) {
pizza_cheese = numCheeseTop;
}
public void setNumPep(int numPepTop) {
pizza_pep = numPepTop;
}
public void setNumHam(int numHamTop) {
pizza_ham = numHamTop;
}
//End of setters
//Getters
public String getPizzaSize() {
return pizza_size;
}
public int getNumCheese() {
return pizza_cheese;
}
public int getNumPep() {
return pizza_pep;
}
public int getNumHam() {
return pizza_ham;
}
//End of getters
public double calcCost() {
if (pizza_size.toLowerCase() == "small") {
return 10 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "medium") {
return 12 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() == "large") {
return 14 + ((pizza_cheese + pizza_pep + pizza_ham) * 2);
}
if (pizza_size.toLowerCase() != "small" && pizza_size.toLowerCase() != "medium"
&& pizza_size.toLowerCase() != "large") {
System.out.println("Invalid pizza size");
return 0;
}
return 0;
}
public String getDescription() {
return pizza_size + " pizza with " + pizza_cheese + " cheese toppings " + pizza_pep + " pepperoni toppings and "
+ pizza_ham + " ham toppings "; //+ " which is " + money.format(pizza2.calcCost());
}
//private String pizza_size;
//private int pizza_cheese, pizza_pep, pizza_ham;
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
} //End of Pizza class
PizzaOrderArray.java
import static java.lang.System.out;
public class PizzaOrderArray {
public String pizza_size;
public int pizza_cheese, pizza_pep, pizza_ham;
//private String pizza_size;
//private int pizza_cheese; pizza_pep; pizza_ham;
private Pizza[] pizza;
private int index = 0;
public PizzaOrderArray() {
System.out.println("PizzaOrderArray()");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(int i) {
System.out.println("PizzaOrderArray(int i)");
index = 1;
pizza = new Pizza[index];
}
public PizzaOrderArray(PizzaOrderArray poa) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa)");
pizza = new Pizza[poa.index];
index = poa.index;
for (int i = 0; i < poa.index; i++) {
System.out.println("PizzaOrderArray(PizzaOrderArray poa) for loop");
pizza[i] = new Pizza(poa.pizza[i]);
}
}
public void setPizza(int index1, Pizza newpizza) {
System.out.println("Inside of setPizza");
pizza[index1] = new Pizza(newpizza);
}
public String getPizzaSize() {
System.out.println("Inside of getPizzaSize");
return pizza_size;
}
public int getNumCheese() {
System.out.println("Inside of getNumCheese");
return pizza_cheese;
}
public int getNumPep() {
System.out.println("Inside of getNumPep");
return pizza_pep;
}
public int getNumHam() {
System.out.println("Inside of getNumHam");
return pizza_ham;
}
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for (int i = 0; i < indexUsed; i++) {
s = (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
return s;
}
public double calcTotal() {
double r = 0.0;
System.out.println("Inside of calcTotal");
for (int i = 0; i < index; i++) {
System.out.println("Inside of calcTotal for loop");
r = r + pizza[i].calcCost();
}
return r;
}
public boolean equals(PizzaOrderArray orderarray) {
boolean r = false;
System.out.println("Inside of equals");
if (orderarray.pizza.length != pizza.length) {
System.out.println("Inside of equals if");
return r;
}
for (int i = 0; i < orderarray.pizza.length; i++) {
if (pizza[i].equals(orderarray.pizza[i])) {
System.out.println("Inside of equals for-if");
r = true;
} else {
System.out.println("Inside of equals for-else");
return false;
}
}
System.out.println("Return of equals");
return r;
}
} //End of PizzaOrderArray class
V4_Project_15_page_418.java
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.Arrays;
public class V4_Project_15_page_418 {
public static void main(String args[]) {
//Order1
PizzaOrderArray order1 = new PizzaOrderArray();
Pizza pizzaone = new Pizza("Medium", 0, 0, 0);
Pizza pizzatwo = new Pizza("Small", 1, 0, 0);
order1.setPizza(0, pizzaone);
System.out.println("Order 1: ");
System.out.println(order1.toString());
System.out.println(order1);
System.out.println();
//Order2
Pizza pizzathree = new Pizza(pizzatwo);
PizzaOrderArray order2 = new PizzaOrderArray(2);
order2.setPizza(0, pizzaone);
order2.setPizza(0, pizzatwo);
System.out.println("Order 2: ");
System.out.println(order2.toString());
System.out.println(order2);
System.out.println();
//Order3
PizzaOrderArray order3 = new PizzaOrderArray(1);
order3.setPizza(0, pizzaone);
order3.setPizza(0, pizzatwo);
System.out.println("Order 3: ");
System.out.println(order3.toString());
System.out.println(order3);
System.out.println();
//Order4
PizzaOrderArray order4 = new PizzaOrderArray(order3);
System.out.println("Order 4: ");
System.out.println(order4.toString());
System.out.println(order4);
//TEST THE PROGRAM
System.out.println("TEST: The total for order 4 is: " + order4.calcTotal());
System.out.println();
//Order5
PizzaOrderArray order5 = new PizzaOrderArray(order1);
System.out.println("Order5: ");
System.out.println(order5);
System.out.println();
}//End of main class
}//End of V4_Project_15_page_418 class
Output:
PizzaOrderArray()
Inside of setPizza
Order 1:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 2:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(int i)
Inside of setPizza
Inside of setPizza
Order 3:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order 4:
Inside of toString
Inside of toString for loop
Inside of toString
Inside of toString for loop
Inside of calcTotal
Inside of calcTotal for loop
Invalid pizza size
TEST: The total for order 4 is: 0.0
PizzaOrderArray(PizzaOrderArray poa)
PizzaOrderArray(PizzaOrderArray poa) for loop
Order5:
Inside of toString
Inside of toString for loop
Take a close look at the condition in this for loop, it isn't going to ever print anything since the condition is never true since i is never less than indexUsed which is 0.
public String toString() {
String s = "";
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
return s;
}
Something also need pay attention to:
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString());
System.out.println("Inside of toString for loop");
means:
for(int i = 0; i < indexUsed; i++) {
s= (s + pizza[i].toString());
}
System.out.println("Inside of toString for loop");
So this is System.out.println just misleading you, you are never "inside of" the for loop.
I think it's better to always use the braces '{}' with for/while loop.
The snippet
int indexUsed = 0;
System.out.println("Inside of toString");
for(int i = 0; i < indexUsed; i++)
s= (s + pizza[i].toString()); is wrong, your for loop is never executed since indexUsed is 0
In your toString method, the for loop condition never becomes true (before the first iteration itself, 0<0 becomes false & loop terminates without executing once) so the loop never executes.
You can try changing the for loop statement to:
for(int i = 0; i < index; i++)

user input still stored after exceeding array length

Can someone see why the user can enter more than 27 apple, blueberry, or peanut pies? Even after declaring a final int for the max number of each type of pie.
The object here is to continually prompt the user for type of pie until the user wants to quit. Each time one of the valid inputs is entered it is stored in it's own array. After the user has indicated they are finished, calculations are done and a message is printed.
import javax.swing.JOptionPane;
public class CalcPieProfit {
public static void main(String[] args) {
final int MAX_PER_TYPE = 27;
int appleTotal = 0;
int blueberryTotal = 0;
int peanutTotal = 0;
String typeOfPie = getPieType();
while (!typeOfPie.equalsIgnoreCase("q")) {
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
else if (typeOfPie.equalsIgnoreCase("blueberry")) {
String[] blueberryArray = fillBlueberry(typeOfPie, MAX_PER_TYPE);
blueberryTotal++;
}
else if (typeOfPie.equalsIgnoreCase("peanut")) {
String[] peanutArray = fillPeanut(typeOfPie, MAX_PER_TYPE);
peanutTotal++;
}
typeOfPie = getPieType();
}
if (typeOfPie.equalsIgnoreCase("q")) {
int totalPies = calcTotalPies(appleTotal, blueberryTotal, peanutTotal);
double profit = calcProfit(appleTotal, blueberryTotal, peanutTotal);
printReport(totalPies, appleTotal, blueberryTotal, peanutTotal, profit);
}
}
public static String getPieType() {
String pieType;
do {
try {
pieType = JOptionPane.showInputDialog("Enter a pie type:");
}
catch (NumberFormatException e) {
pieType = "";
}
if (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q")) {
JOptionPane.showMessageDialog(null, "Enter 'apple', 'blueberry', 'peanut', or 'q' only.");
}
} while (!pieType.equalsIgnoreCase("apple") && !pieType.equalsIgnoreCase("blueberry") &&
!pieType.equalsIgnoreCase("peanut") && !pieType.equalsIgnoreCase("q"));
return pieType;
}
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
public static String[] fillBlueberry(String typeOfPie, int MAX_PER_TYPE) {
String[] blueberryArray = new String[MAX_PER_TYPE];
for (int i = 0; i < blueberryArray.length; i++) {
blueberryArray[i] = typeOfPie;
}
return blueberryArray;
}
public static String[] fillPeanut(String typeOfPie, int MAX_PER_TYPE) {
String[] peanutArray = new String[MAX_PER_TYPE];
for (int i = 0; i < peanutArray.length; i++) {
peanutArray[i] = typeOfPie;
}
return peanutArray;
}
public static int calcTotalPies(int appleTotal, int blueberryTotal, int peanutTotal) {
int total = appleTotal + blueberryTotal + peanutTotal;
return total;
}
public static double calcProfit (int appleTotal, int blueberryTotal, int peanutTotal) {
final double APPLE_PROFIT = 5.94;
final double BLUEBERRY_PROFIT = 5.89;
final double PEANUT_PROFIT = 6.95;
double profit = (APPLE_PROFIT * appleTotal) + (BLUEBERRY_PROFIT * blueberryTotal) +
(PEANUT_PROFIT * peanutTotal);
return profit;
}
public static void printReport(int totalPies, int appleTotal, int blueberryTotal, int peanutTotal, double profit) {
if (totalPies > 0) {
JOptionPane.showMessageDialog(null,
"Pie Report\n\n" +
"Total pies: " + totalPies +
"\nTotal of apple pie: " + appleTotal +
"\nTotal of blueberry pie: " + blueberryTotal +
"\nTotal of peanut butter pie: " + peanutTotal +
"\nTotal profit: $" + String.format("%.2f", profit));
}
else {
JOptionPane.showMessageDialog(null, "Enjoy your day off.");
}
}
}
You are not really using the String[]s appleArray, blueberryArray and peanutArray - they are created in their respective method but not used anywhere else. For calculating the profits, you are (rightfully) only the total variables.
Instead of
if (typeOfPie.equalsIgnoreCase("apple")) {
String[] appleArray = fillApple(typeOfPie, MAX_PER_TYPE);
appleTotal++;
}
you should do something like
if (typeOfPie.equalsIgnoreCase("apple")) {
if (appleTotal >= MAX_PER_TYPE) {
JOptionPane.showMessageDialog(null, "Too many apples.");
} else {
appleTotal++;
}
}
(and the same for other pie types).
You're redeclaring the pie arrays each time you go to add them.
public static String[] fillApple(String typeOfPie, int MAX_PER_TYPE) {
String[] appleArray = new String[MAX_PER_TYPE];
for (int i = 0; i < appleArray.length; i++) {
appleArray[i] = typeOfPie;
}
return appleArray;
}
Each time you call this method, a new "appleArray" is generated. If you want it to persist between calls to this method, declare the appleArray as private static outside of the loop, and reference that instead.

Syntax errors in pizza order program

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.

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

How to pass Parameter value to Instance Variable?

Here are the instructions I have for a class project that I've given up on.
The constructor should call the appropriate set methods of the String class, to assign the values passed as parameters to the instance variables size and toppings
I have a constructor of a Pizza class but it will not keep the parameter values for size and toppings that I pass to it even if I use size = this.size. I don't understand what set method my teacher is referring to. All I need is the conceptual understanding and I will be able to do complete this project.
edit: to be clear, I know my code gives a NPE right now, because my variable toppings is null in toString(), so I'm trying to pass the toppings that has been changed by Pizza() to toString()
public class Pizza {
private char size;
private String[] toppings;
private int status;
public final static int NOT_STARTED = 0;
public final static int IN_PROGRESS = 1;
public final static int READY = 2;
public static void main(String[] args) {
String[] testArray = new String[]{"poop", "pee"};
Pizza newpizza2 = new Pizza('L', testArray);
System.out.println(newpizza2.toString());
}
//Boolean method with a char parameter that checks the size and sets the char of the pizza size (S,M,L) and returns true.
public boolean setSize(char size2) {
if (size2 == 'S'||size2 == 'M'||size2 == 'L') {
size = size2;
return true;
}
else {
size = 'M';
return false;
}
}
//Boolean method with an int parameter that checks the status and sets the status of the pizza readiness.
public boolean setStatus(int status2) {
if (status2 >= NOT_STARTED && status2 <= READY) {
status = status2;
return true;
}
else {
status = NOT_STARTED;
return false;
}
}
//Void method with a String array parameter that only sets the toppings from user input and returns no value.
public void setToppings(String[] toppings) {
toppings = this.toppings;
}
//A Get method for setSize to return the value of size.
public char getSize() {
return this.size;
}
//A Get method for setStatus to return the value of status.
public int getStatus() {
return this.status;
}
//A Get method for setToppings to return the value of toppings[].
public String[] getToppings() {
return this.toppings;
}
//Int method that checks the number of toppings and returns the amount of toppings or 0 if there are no toppings given.
public int numToppings() {
if (toppings != null) {
return toppings.length;
}
else {
return 0;
}
}
//Method that calculates the price of the pizza based on the instance variables and returns the price.
public double calcPrice() {
if (size == 'S') {
double price = 8;
double toppingPrice = toppings.length;
double total = price + toppingPrice;
return total;
}
else if (size =='M') {
double price = 9;
double toppingPrice = 0;
if (toppings != null) {
toppingPrice = toppings.length * 1.5;
}
double total = price + toppingPrice;
return total;
}
else if (size =='L') {
double price = 10;
double toppingPrice = toppings.length * 2;
double total = price + toppingPrice;
return total;
}
else {
return 0;
}
}
/********************************/
//No argument Constructor//
public Pizza() {
size = 'M';
status = NOT_STARTED;
toppings = null;
}
public Pizza(char size, String[] toppings) {
size = this.size;
System.out.println(toppings.length);
status = NOT_STARTED;
}
public String statusPhrase() {
if (status == NOT_STARTED) {
return "Not Started";
}
else if (status == IN_PROGRESS) {
return "In Progress";
}
else {
return "Ready";
}
}
public String toString() {
String combo, combo2 = "", combo3;
Pizza newpizza = new Pizza();
newpizza.setSize(size);
newpizza.setToppings(toppings);
//Print out the method's return values
if (toppings.length == 0) {
combo = "Pizza size " + newpizza.getSize() + ". No toppings.";
}
else {
combo = "Pizza size " + newpizza.getSize() + ". Toppings: ";
}
//List the toppings in number order using a for loop
for (int i = 0; i<=newpizza.numToppings()-1; i++){
combo2 += "\n" + (i+1)+ ". " + newpizza.getToppings()[i];
}
combo3 = "\n"+newpizza.statusPhrase();
return combo + combo2 + combo3;
}
}
It's really simple:
private char someChar;
public void setSomeChar (char someChar) {
this.someChar = someCHar; // 'this' refers to THIS instance.
}
It is also important to know that the thing on the left site is the one the value gets passed to (excuse my english).
When you write:
private char someChar;
public void setSomeChar (char someChar) {
someChar = this.someCHar; //
}
you pass the value of the instance variable to the local method parameter (they coincidentally have the same name).
To say it a little more generally:
private char instanceVariable;
public void someMethod (char someLocalParameter) {
/* local means that it is only known inside this method. That's why everything
* you assign to it just disappears after executing the method.
*/
someLocalParameter = this.instanceVariable // nothing happens
this.instanceVariable = someLocalParameter // will do the job
}
This your current constructor
public Pizza(char size, String[] toppings) {
size = this.size;
System.out.println(toppings.length);
status = NOT_STARTED;
}
Your constructor should look like this
public Pizza(char size, String[] toppings) {
this.size = size;
this.toppings = toppings
System.out.println(toppings.length);
status = NOT_STARTED;
}

Categories

Resources