# Thread: HW Help: If-Else-If

1. Member
Join Date
Feb 2010
Posts
14
Rep Power
0

## HW Help: If-Else-If

Something tells me I'm missing something very simple that I'm just not seeing out of frustration. Basically the assignment is setting up a pizza ordering program. User inputs name, size, toppings and calculates the cost. I'm stuck on inputing the sizes using if-else-if. Both scripts are supplied I have to edit one. My issue is my if else if is not working for the accepting of the pizza size. No matter what it is always outputs the pizza size at 12 inches (defaulted by the class file I am not to edit), yet I'm getting no errors to help me pin point my problem.

Here is the program I am working with (in red is where I'm stuck).
Java Code:
```//This program allows the user to order a pizza

import java.util.Scanner;
//TASK #5 add an import statement to use the DecimalFormat class

public class PizzaOrder
{
public static void main (String [] args)
{
//TASK #5 Create a DecimalFormat object with 2 decimal places

//Create a Scanner object to read input
Scanner keyboard = new Scanner (System.in);

//Create an instance of a Pizza
Pizza order = new Pizza ();

String firstName;		//user's first name
boolean discount = false;//flag, true if user is eligible for discount
int inches;				//size of the pizza
char crustType;			//type of crust
double cost;			//cost of the pizza
final double TAX_RATE = .08;//sales tax rate
double tax;				//amount of tax
char choice;			//user's choice
String input;			//user input
String toppings = "Cheese ";//list of toppings
int numberOfToppings = 0;	//number of toppings

//prompt user and get first name
System.out.println("Welcome to Mike and Diane's Pizza");
System.out.print("Enter your first name:  ");
firstName = keyboard.nextLine();

//determine if user is eligible for discount by
//having the same first name as one of the owners
if (firstName.compareToIgnoreCase("Mike") == 0)
{
discount = true;
}
else if (firstName.compareToIgnoreCase("Diane") == 0)
{
discount = true;
}

//prompt user and get pizza size choice
System.out.println("Pizza Size (inches)   Cost");
System.out.println("        10            \$10.99");
System.out.println("        12            \$12.99");
System.out.println("        14            \$14.99");
System.out.println("        16            \$16.99");
System.out.println("What size pizza would you like?");
System.out.print("10, 12, 14, or 16 (enter the number only): ");
inches = keyboard.nextInt();

[COLOR="Red"]//set price and size of pizza ordered

{
int diameter;

if (inches == 10)
diameter = 10;

else if (inches == 12)
diameter = 12;

else if (inches == 14)
diameter = 14;

else if (inches == 16)
diameter = 16;
}[/COLOR]

//consume the remaining newline character
keyboard.nextLine();

//prompt user and get crust choice
System.out.println("What type of crust do you want? ");
System.out.print("(H)Hand-tossed, (T) Thin-crust, or " +
"(D) Deep-dish (enter H, T, or D): ");
input = keyboard.nextLine();
crustType = input.charAt(0);

//set user's crust choice on pizza ordered
//ADD LINES FOR TASK #3

//prompt user and get topping choices one at a time
System.out.println("All pizzas come with cheese.");
System.out.println("Additional toppings are \$1.25 each,"
+ " choose from");
System.out.println("Pepperoni, Sausage, Onion, Mushroom");

//if topping is desired,
//add to topping list and number of toppings
System.out.print("Do you want Pepperoni?  (Y/N):  ");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'Y' || choice == 'y')
{
numberOfToppings += 1;
toppings = toppings + "Pepperoni ";
}
System.out.print("Do you want Sausage?  (Y/N):  ");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'Y' || choice == 'y')
{
numberOfToppings += 1;
toppings = toppings + "Sausage ";
}
System.out.print("Do you want Onion?  (Y/N):  ");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'Y' || choice == 'y')
{
numberOfToppings += 1;
toppings = toppings + "Onion ";
}
System.out.print("Do you want Mushroom?  (Y/N):  ");
input = keyboard.nextLine();
choice = input.charAt(0);
if (choice == 'Y' || choice == 'y')
{
numberOfToppings += 1;
toppings = toppings + "Mushroom ";
}

//set number of toppings and topping list on pizza ordered
order.setNumToppings (numberOfToppings);
order.setToppingList(toppings);

//add additional toppings cost to cost of pizza
order.setCost(1.25*numberOfToppings);

//display order confirmation
System.out.println();
System.out.println("Your order is as follows: ");
System.out.println(order.getSize() + " inch pizza");
System.out.println(order.getCrust() + " crust");
System.out.println(order.getToppingList());

//display cost of pizza
cost = order.getCost();

//apply discount if user is elibible
//ADD LINES FOR TASK #4 HERE

//EDIT PROGRAM FOR TASK #5
//SO ALL MONEY OUTPUT APPEARS WITH 2 DECIMAL PLACES
System.out.println("The cost of your order is: \$" + cost);

//calculate and display tax and total cost
tax = cost * TAX_RATE;
System.out.println("The tax is:  \$" + tax);
System.out.println("The total due is:  \$" + (tax+cost));

System.out.println("Your order will be ready" +
" for pickup in 30 minutes.");
}
}```

And here is the class file.
Java Code:
```//This program will represent a pizza

public class Pizza
{
private double cost;				//the cost of the pizza
private String crust;			//the type of crust
private int size;					//the diameter in inches
private int numToppings;		//the number of toppings
private String toppingList;	//a list of the toppings

//Constructor creates a 12" Hand-tossed pizza
public Pizza()
{
cost = 12.99;
crust = "Hand-tossed";
size = 12;
numToppings = 0;
toppingList = null;
}

//adds the parameter amount to the cost
public void setCost (double amount)
{
cost += amount;
}

//sets the crust type
public void setCrust (String type)
{
crust = type;
}

//changes the size of the pizza to the parameter diameter
public void setSize (int diameter)
{
size = diameter;
}

//sets the number of toppings to the parameter number
public void setNumToppings(int number)
{
numToppings = number;
}

//sets the list of toppings
public void setToppingList (String newTopping)
{
toppingList = newTopping;
}

//returns the cost of the pizza
public double getCost()
{
return cost;
}

//returns the crust type
public String getCrust()
{
return crust;
}

//returns the size of the pizza
public int getSize()
{
return size;
}

//returns the number of toppings
public int getNumToppings()
{
return numToppings;
}

//returns the list of toppings
public String getToppingList()
{
return toppingList;
}
}```

As an example here is an output after I inputed a 16 inch pizza
Your order is as follows:
12 inch pizza
Hand-tossed crust
Cheese
The cost of your order is: \$12.99
The tax is: \$1.0392000000000001
The total due is: \$14.0292
Your order will be ready for pickup in 30 minutes.

If this helps heres the specific task details from my lab manual
1. Write an if-else-if statement that lets the computer choose which statements to
execute by the user input size (10, 12, 14, or 16). For each option, two statements
need to be executed:
a) A call to the setSize method passing in the size indicated.
b) A call to the setCost method passing in the appropriate adjustment. Notice
that in the Pizza.java program, the constructor creates a 12 inch Handtossed
pizza for \$12.99. The setCost method adjusts the cost, so a 10 inch
pizza will need its cost decreased by 2, while the 16 inch pizza cost will
need to increase by 4.
2. The default else of the above if-else-if statement should print a statement that
the user input was not one of the choices, so a 12 inch pizza will be made.
3. Compile, debug, and run. You should now be able to get correct output for size
and price (it will still have Hand-tossed crust, the output won’t look like money,
and no discount will be applied yet). Run your program multiple times ordering
a 10, 12, 14, 16, and 17 inch pizza.
Thank you a ton in advanced.
Last edited by gto400no1; 03-16-2010 at 12:53 AM.

2. With this:
Java Code:
```		{
int diameter;

if (inches == 10)
diameter = 10;

else if (inches == 12)
diameter = 12;

else if (inches == 14)
diameter = 14;

else if (inches == 16)
diameter = 16;
}```
All you're really doing is this:
Java Code:
`int diameter = inches;`
but in a much more verbose and unnecessarily redundant manner. Do you really want to do this? Wouldn't you rather use the inches information and output a cost instead? It's really more logic here than programming that will solve your problem I think.

Edit: I see that your assignment hand out tells you exactly what you need to do. In this if/else block, call the methods that the assignment is suggesting you call and the program should work. Please give it a try and come back with this attempt if it doesn't work.

Much luck!
Last edited by Fubarable; 03-16-2010 at 01:40 AM.

3. Hint number two: the two methods mentioned in your assignment requirements are methods of the Pizza class. Your PizzaOrder class just so happens to have a Pizza object called order, so you should call these methods on your ____ object (fill in the blank). ;)

Much luck!

4. Member
Join Date
Feb 2010
Posts
14
Rep Power
0
Thank you very much I think that will help me a ton!

5. Originally Posted by gto400no1
Thank you very much I think that will help me a ton!
Cool I hope so. And actually I made a mistake in the above post. Your PizzaOrder class has a Pizza variable called order that references a Pizza object. It seems an insignificant distinction, but as you'll learn, it's not. Sorry for the misinformation and best of luck.

6. Senior Member
Join Date
Mar 2010
Posts
953
Rep Power
4
Originally Posted by Fubarable
Cool I hope so. And actually I made a mistake in the above post. Your PizzaOrder class has a Pizza variable called order that references a Pizza object. It seems an insignificant distinction, but as you'll learn, it's not. Sorry for the misinformation and best of luck.
@gto400no1: And this, I think, is a bad thing. You have a class called Pizza and a class called PizzaOrder, and you want to give something of type Pizza the name "order"? Programming can be confusing enough without adding to it unnecessarily. Call your Pizza object "pizza".

Also, if your instructor wants you do everything using local variables in your main() method, OK (I guess). But if you have a choice, then you should be breaking your code up into methods, and giving your PizzaOrder class some instance variables, with appropriate getter and setter methods. Even though it seems like more work, it's much less confusing in the long run.

-Gary-

7. Member
Join Date
Feb 2010
Posts
14
Rep Power
0
Alright got the size selection working, but I seem to be doing something wrong with calling the setCost method. I have this currently...

Java Code:
```	//set price and size of pizza ordered
{
int diameter = inches;
order.setSize(diameter);
double amount = cost;
order.setCost(amount);

if (diameter == 10)
amount = 10.99;

else if (inches == 12)
amount = 12.99;

else if (inches == 14)
amount = 14.99;

else if (inches == 16)
amount = 16.99;

else
System.out.println("Input not a choice, so a 12 inch pizza will be made.");
}```

Says cost might not be initialized, but it is!?
Last edited by gto400no1; 03-16-2010 at 11:03 PM.

8. OK, the best way to solve this is to think logically through this code as if you were the computer. Your situation above is analogous to this code below:

Java Code:
```int sum = 0;
System.out.println("sum = " + sum);

sum = 5 + 7;```
The output will be 0 because I'm working with my sum result before I've done the addition. Can you see how this applies to your code above?

9. Member
Join Date
Feb 2010
Posts
14
Rep Power
0
I see why you answer would be 0, because the output is before the sum = 5 + 7;. So then I though ok maybe I need to call the method at the end? Did that but still got the same results.

Java Code:
```	//set price and size of pizza ordered
{
int diameter = inches;
order.setSize(diameter);

if (inches == 10)
cost = 10.99;

else if (inches == 12)
cost = 12.99;

else if (inches == 14)
cost = 14.99;

else if (inches == 16)
cost = 16.99;

else
System.out.println("Input not a choice, so a 12 inch pizza will be made.");

double amount = cost;
order.setCost(amount);

}```

10. Member
Join Date
Feb 2010
Posts
14
Rep Power
0
Correction, was doing it wrong and think this is what you meant. But what I don't understand is why what ever the result of this statement is, the program adds 12.99 to the total.
Java Code:
```
//set price and size of pizza ordered
{
int diameter = inches;
order.setSize(diameter);
cost = order.getCost();

if (inches == 10)
cost -= 2;

else if (inches == 12);
cost = 12.99;

else if (inches == 14)
cost += 2;

else if (inches == 16)
cost += 4;

else
System.out.println("Input not a choice, so a 12 inch pizza will be made.");

double amount = cost;
order.setCost(amount);

}```
Last edited by gto400no1; 03-17-2010 at 01:08 AM.

11. Senior Member
Join Date
Mar 2009
Posts
552
Rep Power
5
If I'm reading the assignment criteria right, setCost ADJUSTS the cost, but does not absolutely set it. So:

A: you are always getting inches == 12 as true and setting cost to 12.99.
B: you then use the value of 12.99 in the cost variable and adding that to the original cost when you call setCost (Horrible horrible horrible! Especially in java! Should be something like adjustCost or increaseCost...)

Which means that you have bugs in your input code, and in your if-else if-else block. You don't need to adjust the cost if the pizza size is 12", (though setting cost to 0 which does not change the value if setCost is called with it is fine.

Set up your condition blocks to reflect that the call to setCost is adding the amount in the parameter to the original cost, and fix your input retrieval, and you should be fine... Not sure what the problem with the input is... its probably getting the right value, but you're losing it somewhere or forgetting to call a method or set something. You have the right value, but it's not getting copied into the right variable.

This is why we have private methods and split the job into smaller, doable tasks... so its easier to figure out where you lost the value or what you forgot to do! Can you write a compiler in one method? Not a chance!(And we still spend hours looking for the missed addActionListener call...)

So... split your method into smaller chunks, move things like the Pizza to being static variables. If a method does more than one or maybe two tasks, you have a problem, so break that method up. If you have a single task that takes more than 20 lines of code, it's too long, so break it into smaller tasks (for now at least, later on you may run into times where you can't split it up without making awkward code). In short, follow the KISS principle... Keep It Simple, Sherlock!

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•