Java Fast Food Menu (using methods) - java

I'm writing a program that displays a fast food menu. The user selects an item, then enters the quantity of that item, and can continue selecting items with specific quantities until done. I have to use several methods. What I'm having trouble with is calculating a running total. This is my first Java class so I only know the basics. I put the running total in a while loop so it'll keep adding a subtotal to it, but when I call done() the runningTotal is 0. What's the best way to keep track of the running total while using multiple methods? Also, I'm open to any criticism or clean up in my code. Thank you.
import java.util.Scanner;
public class Menu {
public double subTotal;
public static double runningTotal;
private static double itemPrice;
static boolean ordering = true;
static Scanner input = new Scanner(System.in);
public static void menu() {
System.out.println("Welcome \n1. Burger ($2.00) \n2. Fries ($1.50)\n3. Soda ($1.00) \n4. Done");
}
public static double itemPrice(int foodItem) {
if (foodItem == 1) {
// burger= $2.00
System.out.println("You've ordered a burger");
itemPrice = 2.00;
}
if (foodItem == 2) {
// fries = $1.50
System.out.println("You've ordered fries");
itemPrice = 1.50;
}
if (foodItem == 3) {
// soda = $1.00
System.out.println("You've ordered a soda");
itemPrice = 1.00;
}
quantity();
return itemPrice;
}
public static double quantity() {
System.out.println("Enter quantity");
double quantity = input.nextDouble();
subTotal(quantity, itemPrice);
return quantity;
}
public static double subTotal(double quantity, double itemPrice) {
double subTotal = quantity * itemPrice;
System.out.println("Subtotal: " + subTotal);
return subTotal;
}
public static void done(double runningTotal) {
ordering = false;
System.out.println(runningTotal);
System.out.println("Enjoy your meal");
}
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
do {
double runningTotal = 0;
menu();
menuOption = input.nextInt();
switch (menuOption) {
case 1:
foodItem = 1;
itemPrice(foodItem);
break;
case 2:
foodItem = 2;
itemPrice(foodItem);
break;
case 3:
foodItem = 3;
itemPrice(foodItem);
break;
case 4:
done(runningTotal);
break;
default:
System.out.println("Invalid option.");
}
} while (ordering);
{
subTotal(quantity(), itemPrice(foodItem));
runningTotal = runningTotal + subTotal(quantity(), itemPrice(foodItem));
}
}
}

You are resetting the double runningTotal=0; in the while loop. Also the price returned by the itemPrice needs to be added into the runningTotal variable;
This is how your main method should look like. You are not required to call the subTotal method, once the user is done.
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
double runningTotal=0;
do{
menu();
menuOption = input.nextInt();
switch(menuOption){
case 1:
foodItem = 1;
runningTotal += itemPrice(foodItem);
break;
case 2:
foodItem = 2;
runningTotal += itemPrice(foodItem);
break;
case 3:
foodItem = 3;
runningTotal += itemPrice(foodItem);
break;
case 4:
done(runningTotal);
break;
default:
System.out.println("Invalid option.");
}
} while(ordering);
System.out.println("Total amount: " + runningTotal);
}
Output:
Welcome
1. Burger ($2.00)
2. Fries ($1.50)
3. Soda ($1.00)
4. Done
1
You've ordered a burger
Enter quantity
2
Subtotal: 4.0
Welcome
1. Burger ($2.00)
2. Fries ($1.50)
3. Soda ($1.00)
4. Done
2
You've ordered fries
Enter quantity
1
Subtotal: 1.5
Welcome
1. Burger ($2.00)
2. Fries ($1.50)
3. Soda ($1.00)
4. Done
4
3.5
Enjoy your meal
Total amount: 3.5

You reset runningTotal to 0 every iteration. I have attached a working example. I moved the total calculation to your subTotal method where it adds every subTotal as they come in.
import java.util.Scanner;
public class menu {
public double subTotal;
public static double runningTotal;
private static double itemPrice;
static boolean ordering = true;
static Scanner input = new Scanner(System.in);
public static void menu(){
System.out.println("Welcome \n1. Burger ($2.00) \n2. Fries ($1.50)\n3. Soda ($1.00) \n4. Done");
}
public static double itemPrice(int foodItem) {
if (foodItem == 1) {
//burger= $2.00
System.out.println("You've ordered a burger");
itemPrice = 2.00;
}
if (foodItem == 2) {
//fries = $1.50
System.out.println("You've ordered fries");
itemPrice = 1.50;
}
if (foodItem == 3) {
//soda = $1.00
System.out.println("You've ordered a soda");
itemPrice = 1.00;
}
quantity();
return itemPrice;
}
public static double quantity() {
System.out.println("Enter quantity");
double quantity = input.nextDouble();
subTotal(quantity, itemPrice);
return quantity;
}
public static double subTotal(double quantity, double itemPrice) {
double subTotal = quantity*itemPrice;
System.out.println("Subtotal: "+ subTotal);
runningTotal += subTotal;
return subTotal;
}
public static void done(){
ordering = false;
System.out.println(runningTotal);
System.out.println("Enjoy your meal");
}
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
do{
double runningTotal=0;
menu();
menuOption = input.nextInt();
switch(menuOption){
case 1:
foodItem = 1;
itemPrice(foodItem);
break;
case 2:
foodItem = 2;
itemPrice(foodItem);
break;
case 3:
foodItem = 3;
itemPrice(foodItem);
break;
case 4:
done();
break;
default:
System.out.println("Invalid option.");
}
} while(ordering); {
}
}
}

This will bring the exact output.
import java.util.Scanner;
public class Resteraunt
{
public double subTotal;
public static double runningTotal;
private static double itemPrice;
static boolean ordering = true;
static Scanner input = new Scanner(System.in);
static double j=0.0;
public static void main(String[] args) {
int menuOption;
int foodItem = 0;
input = new Scanner(System.in);
double runningTotal=0;
while(ordering)
{
menu();
menuOption = input.nextInt();
switch(menuOption){
case 1:
foodItem = 1;
runningTotal += ItemPrice(foodItem);
break;
case 2:
foodItem = 2;
runningTotal += ItemPrice(foodItem);
break;
case 3:
foodItem = 3;
runningTotal += ItemPrice(foodItem);
break;
case 4:
done(runningTotal);
break;
default:
System.out.println("Invalid option.");
}
}
System.out.println("Total amount: $" + runningTotal);
}
public static void menu() {
System.out.println("Welcome \n1. Burger ($2.00) \n2. Fries ($1.50)\n3. Soda
($1.00) \n4. Done");
}
public static double ItemPrice(int foodItem) {
if (foodItem == 1) {
// burger= $2.00
System.out.println("You've ordered a burger");
itemPrice = 2.00;
}
if (foodItem == 2) {
// fries = $1.50
System.out.println("You've ordered fries");
itemPrice = 1.50;
}
if (foodItem == 3) {
// soda = $1.00
System.out.println("You've ordered a soda");
itemPrice = 1.00;
}
quantity();
return j;
}
public static double quantity() {
System.out.println("Enter quantity");
double quantity = input.nextDouble();
subTotal(quantity, itemPrice);
return quantity;
}
public static double subTotal(double quantity, double itemPrice) {
double subTotal = quantity * itemPrice;
System.out.println("Subtotal: $" + subTotal);
j=subTotal;
return subTotal;
}
public static void done(double runningTotal) {
ordering = false;
System.out.println("Enjoy your meal");
}
}

Related

cannot resolve or is not a field error

I am trying to search an arraylist of objects for an ID code, but I am stuck.
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1:
addTransaction(argList);
break;
case 2:
;// Search Transaction
break;
case 3:
;// Filter Withdraws and Deposits
break;
case 4:
;// Display transactions
break;
case 5:
System.out.println("End");
break;
default:
System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription) ); }
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.argId.get(i).contains(searchId)){
System.out.println("Yes");
}
}
}
}
My second file contains this
public class Transaction {
int id;
char type;
double amount;
String description;
public Transaction(int argId, double argAmount,char argType, String
argDescription){
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public void getId(int id){
}
public void getAmount(double amount){
}
public void getType(char type){
}
public void getDescription(String description){
}
}
And i get the error message: argId cannot be resolved or is not a field on line 58. I think my error is that argId is not part of the ArrayList, and i need to find the right tern to search the ID codes in the ArrayList.
Thanks
Earlier, before you edited your question, you had wrong getter methods.
Instead of
public void getId(int id){
}
you should write this:
public int getId() {
return id;
}
Declare your fields in Transaction class as private.
Then change your other getters in the similar way.
About your actual question, you can use for-each loop:
public static void searchTransactions(ArrayList<Transaction> argList) {
try (Scanner input = new Scanner(System.in)) {
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for (Transaction transaction : argList) {
if (transaction.getId() == searchId) {
System.out.println("Yes");
break;
}
}
}
}
If you insist for i loop, change it this way:
for (int i = 0; i < argList.size(); i++) {
if(argList.get(i).getId() == searchId){
System.out.println("Yes");
break;
}
}
ArgId is a property of the objects in the list, not a property of the list itself which is why the compiler is giving you an error.
Looks like a typo:
You have:
argList.argId.get(i).contains(searchId)
try using:
argList.get(i).argId.contains(searchId)
argList is a collection, then you get object, read argId and check if it contains searchId
I would suggest to encapsulate class Transaction:
public class Transaction {
private int id;
private char type;
private double amount;
private String description;
public Transaction(int argId, double argAmount, char argType, String argDescription) {
id = argId;
type = argType;
amount = argAmount;
description = argDescription;
}
public int getId() {
return id;
}
public char getType() {
return type;
}
public double getAmount() {
return amount;
}
public String getDescription() {
return description;
}
}
Then main class will look in this way:
import java.util.Scanner;
import java.util.ArrayList;
public class Homework01{
public static void main(String[] args){
ArrayList<Transaction> argList = new ArrayList<Transaction>();
Scanner input = new Scanner(System.in);
System.out.println("Transaction List Menu");
System.out.println("=====================");
System.out.println("1) Add Transaction.");
System.out.println("2) Search Transactions.");
System.out.println("3) Filter.");
System.out.println("4) Display All Transactions.");
System.out.println("5) Exit.");
int menu = input.nextInt();
while (menu != 5) {
switch (menu) {
case 1: ; addTransaction(argList);
break;
case 2: ;// Search Transaction
break;
case 3: ;// Filter Withdraws and Deposits
break;
case 4: ;// Display transactions
break;
case 5: System.out.println("End");
break;
default: System.out.println("Invalid response");
break;
}
menu = input.nextInt();
}
}
public static void addTransaction(ArrayList<Transaction> argList) {
Scanner input = new Scanner(System.in);
int tempId;
double tempAmount;
char tempType;
String tempDescription;
System.out.println("Enter in an ID for the transaction: ");
tempId = input.nextInt();
System.out.println("Enter in the amount of money: ");
tempAmount = input.nextDouble();
System.out.println("W for withdraw, D for deposit: ");
tempType = input.next(".").charAt(0);
System.out.println("Give transaction a description: ");
tempDescription = input.next();
//add transaction
argList.add(new Transaction(tempId, tempAmount, tempType, tempDescription)
);
}
public static void searchTransactions(ArrayList<Transaction> argList){
Scanner input = new Scanner(System.in);
System.out.println("Please type in transaction ID: ");
int searchId = input.nextInt();
for(int i=0;i<argList.size();i++){
if(argList.get(i).getId()==searchId){
System.out.println("Yes");
}
}
}
}

update a variable in a different class

How do I make amount() in class Casino.java store the total value and allow it to be returned to the class Roulette.java.
When I use:
int amount = Casino.amount();
It gives me several hundred lines of errors.
What I want done is to run the game number() and store the value into Casino.amount()
Please note in class Roulette.java there is a function called amountUpdate() which should update Casino.amount().
This is class Casino.java
package Casino;
import java.util.*;
public class Casino {
static String player = "";
static int playAmount = 0;
public static void main(String[] args) {
System.out.println("Welcome to Michael & Erics Casino!");
player();
ask();
start();
}
public static String player() {
if (player.equals("")) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter your name : ");
player = sc.nextLine();
}
return player;
}
public static void ask() {
Scanner sc = new Scanner(System.in);
System.out.println("How much would you like to play with? ");
playAmount = sc.nextInt();
if (playAmount < 1) {
System.out.println("Please enter a value that is more than $1");
playAmount = 0;
}
System.out.println("You are playing with: $" + playAmount + "\n");
}
public static int amount() {
int amount = playAmount;
if (Roulette.amountUpdate() >= 1) {
amount += Roulette.amountUpdate();
}
return amount;
/*if (Blackjack.amountUpdate() >= 1)
amount += Blackjack.amountUpdate();
return amount;*/
}
public static void start() {
System.out.println("Which table would you like to play at?");
System.out.println("1: Blackjack");
System.out.println("2: Roulette");
System.out.println("3: Check Balance");
System.out.println("4: Exit");
Scanner sc = new Scanner(System.in);
int table = sc.nextInt();
switch (table) {
case 1:
//blackjack.main(new String[]{});
break;
case 2:
Roulette.main(new String[]{});
break;
case 3:
System.out.println("You have : $" + playAmount);
start();
break;
case 4:
System.exit(0);
break;
}
}
}
This is class Roulette.java
package Casino;
import java.util.*;
import java.lang.*;
public class Roulette {
public static void main(String[] args) {
System.out.println("Welcome to the roulette table " + Casino.player());
placeBet();
amountUpdate();
//number();
}
public static int amountUpdate() {
int amount = 0;
if (number() > 0) {
amount += number();
}
if (br() > 0) {
amount += br();
}
if (oe() > 0) {
amount += oe();
}
if (third() > 0) {
amount += third();
}
return amount;
}
public static void placeBet() {
Scanner sc_Choice = new Scanner(System.in);
System.out.println("What would you like to bet on?");
System.out.println("1: Numbers");
System.out.println("2: Black or Red");
System.out.println("3: Odd or Even");
System.out.println("4: One Third");
System.out.println("5: Count Chips");
System.out.println("6: Restart");
int choice = sc_Choice.nextInt();
if (choice > 0 && choice < 7) {
switch (choice) {
case 1:
number();
break;
case 2:
br();
break;
case 3:
oe();
break;
case 4:
third();
break;
case 5:
System.out.println(Casino.amount());
break;
case 6:
Casino.main(new String[]{});
break;
}
} else {
System.out.println("You must choose between 1 and 6");
}
}
public static int number() {
Boolean betting = true;
//int amount = Casino.amount();
int amount = 5000;
int number;
int winnings;
String reply;
int betX;
int betAgain = 1;
Scanner sc_Number = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> bet = new ArrayList<Integer>();
while (betAgain == 1) {
System.out.println("What number would you like to place a bet on?");
int listCheck = sc_Number.nextInt();
if (listCheck >= 0 && listCheck <= 36) {
list.add(listCheck);
} else {
System.out.println("You must choose a number between 0 and 36");
}
System.out.println("How much do you want to bet?");
betX = sc_Number.nextInt();
if (betX > amount) {
System.out.println("You have insufficient funds to make that bet");
number();
} else if (betX < 1) {
System.out.println("You must bet more than 1$");
} else {
bet.add(betX);
amount = amount - betX;
}
System.out.println("Do you want to bet on more numbers?");
reply = sc_Number.next();
if (reply.matches("no|No|false|nope")) {
betAgain = betAgain - 1;
//No - Don't bet again
} else {
betAgain = 1;
//Yes - Bet again
}
int result = wheel();
System.out.println("Spinning! .... The number is: " + result);
for (int i = 0; i < bet.size(); i++) {
if (list.get(i) == result) {
winnings = bet.get(i) * 35;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
betAgain = betAgain - 1;
}
}
betAgain = betAgain - 1;
}
return amount;
}
public static int wheel() {
Random rnd = new Random();
int number = rnd.nextInt(37);
return number;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int br() {
Scanner sc_br = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Black or Red?");
String replyBR = sc_br.nextLine();
boolean black;
//****************
if (replyBR.matches("black|Black")) {
black = true;
} else {
black = false;
}
System.out.println("How much would you like to bet?");
int betBR = sc_br.nextInt();
if (betBR > amount) {
System.out.println("You have insufficient funds to make that bet");
br();
} else if (betBR < 1) {
System.out.println("You must bet more than 1$");
br();
} else {
amount = amount - betBR;
}
//*****************
boolean resultColour = colour();
if (resultColour == black) {
winnings = betBR * 2;
//PRINT OUT WHAT COLOUR!!!
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
}
System.out.println("Current Balance: " + amount);
return amount;
}
public static boolean colour() {
Random rnd = new Random();
boolean colour = rnd.nextBoolean();
return colour;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int oe() {
Scanner sc_oe = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on Odd or Even?");
String replyOE = sc_oe.next();
System.out.println("How much would you like to bet?");
int betOE = sc_oe.nextInt();
if (betOE > amount) {
System.out.println("You have insufficient funds to make that bet");
oe();
}
amount = amount - betOE;
boolean resultOE = oddOrEven();
//PRINT OUT IF IT WAS ODD OR EVEN
if (resultOE == true) {
winnings = betOE * 2;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean oddOrEven() {
Random rnd = new Random();
boolean num = rnd.nextBoolean();
return num;
}
//NOT WORKING - AFTER MAKING A BET IT RUNS Number()
public static int third() {
Scanner sc_Third = new Scanner(System.in);
int amount = Casino.amount();
int winnings;
System.out.println("Would you like to bet on 1st, 2nd or 3rd third?");
String replyT = sc_Third.next();
System.out.println("How much would you like to bet?");
int betT = sc_Third.nextInt();
if (betT > amount) {
System.out.println("You have insufficient funds to make that bet");
third();
}
amount = amount - betT;
boolean resultT = thirdResult();
//PRINT OUT WHAT NUMBER IT WAS AND IF IT WAS IN WHICH THIRD
if (resultT == true) {
winnings = betT * 3;
System.out.println("Congratulations!! You won: $" + winnings);
amount = amount + winnings;
System.out.println("Current Balance: " + amount);
} else {
System.out.println("Sorry, better luck next time!");
System.out.println("Current Balance: " + amount);
}
return amount;
}
public static boolean thirdResult() {
Random rnd = new Random();
int num = rnd.nextInt(2);
if (num == 0) {
return true;
} else {
return false;
}
}
}
Looks like you're probably running into a StackOverflowException. When you call Casino.amount() inside of Roulette.number(), it then calls Roulette.amountUpdate(), which then calls Roulette.number(). Your methods are stuck in an infinite loop like this. You'll need to redesign your code such that these 3 functions are not all dependent on each other.
Your code is terse, so it's hard to help you fully solve the problem, but I believe you would benefit from splitting up your "amount" variable into separate entities. Keep things like bet amount, winnings, and such separate until you need to combine them.
Another issue you may run into is thatRoulette.amountUpdate() is called twice in Casino.amount(), but Roulette.amountUpdate() will not necessarily return the same thing both times. Consider storing the return value from the first call instead of calling it twice.

Why is case 2 printing when I enter 2?

I am working on a program that tracks items and their costs as you add them to you bag. I have switch statement to give options for 1. adding new items, 2. printing the totals, and 3. ending the program.
For some reason when I select case 1 it also prints the totals using my toString method. But I only have the toString method in case 2.
Can anyone explain why this would be happening?
Here is my main
import java.util.Scanner;
public class ShoppingBagTracker {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
float taxRate, cost;
int items, newItems, choice;
String receipt;
String menu = ("1. Add items" +
"2. Get receipt"
+ "3. Exit");
System.out.print("Enter the sales tax rate: ");
taxRate = in.nextFloat();
ShoppingBag myBag = new ShoppingBag(taxRate);
items = 0;
do{
System.out.println("What would you like to do?");
System.out.println(menu);
choice = in.nextInt();
switch(choice){
case 1:
System.out.print("Enter cost of item: ");
cost = in.nextFloat();
System.out.print("Enter number of items: ");
newItems = in.nextInt();
items = items + newItems;
myBag.place(items, cost);
myBag.getItems();
myBag.getCost();
myBag.getTotal();
myBag.getAverage();
case 2:
receipt = myBag.toString();
System.out.println(receipt);
case 3:
break;
default:
System.out.println("That is not an option");
}
}while(choice != 3);
}
}
Here is my Shopping Bag class
public class ShoppingBag {
public float taxRate;
public int items;
public float cost;
public float average;
public float totalCost;
public float finalCost;
public ShoppingBag(float taxRate)
{
this.taxRate = taxRate;
}
public void place(int newitems, float newcost)
{
items = newitems;
cost = newcost;
cost = items * cost;
}
public int getItems()
{
return items;
}
public float getCost()
{
return cost;
}
public float getTotal()
{
finalCost = cost + (cost * taxRate);
return finalCost;
}
public float getAverage()
{
average = finalCost/items;
return average;
}
#Override
public String toString()
{
return("Items: " + items + " Cost: " + cost + " Total cost: " + finalCost + " Average cost: " + average);
}
}
A switch case isn't restrict to execute one 'case'. It execute all code from the matching case down to a break; or to the end of the switch.
In your case add a break; before the case 2
You need to have break in switch-cases.
switch(something){
case 1:
// do something
break;
case 2:
//do something
break;
default:
// do something
break;
}
If there is no break, that will execute all cases here.
switch-cases in Java.
Conclusion.
If there is no return in cases, you should use break for every case.
Following case you don't need break.
switch (cases){
case "a":
return "a";
case "b":
return "b";
default:
return "default";
}
You need to add a break statement inside the case 1 body
case 1:
System.out.print("Enter cost of item: ");
cost = in.nextFloat();
System.out.print("Enter number of items: ");
newItems = in.nextInt();
items = items + newItems;
myBag.place(items, cost);
myBag.getItems();
myBag.getCost();
myBag.getTotal();
myBag.getAverage();
break;
Here is the official tutorial
You should either have a break for all the cases or have a return statements in all cases. Otherwise when Java will execute all the cases which are after the matching case.
swicth(urSwitch){
case 1:// logic
break; // or return something
case 2:// logic
break; // or return something
case 3:// logic
break; // or return something
}

i m unable to calculate the total after loop

i m unable to calculate the total poperty price and commision help plzzz
my variables are prop and commission
program run perfect but the transaction summarry lead to last loop calculation i need to total all of loop calculation i made
import java.util.Scanner;
public class loopingS {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
String code, decision;
int price =0;
double residential, commercial, multidwelling;
boolean yesno = true;
boolean repeat = true;
boolean cde = true;
double total=0;
boolean yn = true;
double prop=0;
double commission=0;
System .out.println("Real-estate Commission Calculator");
System.out.println("----------------------------------");
while (yn){
while(repeat){
System.out.print("Enter property's selling price: ");
price = kbd.nextInt();
if (price <= 0) {
System.out.println("**error**selling price must be greater than zero ");
repeat = true;
}
else{
prop=0 + price;
while(cde){
System.out.println("residential R\nmulti-dwelling M\nCommercial C");
System.out.println("Enter property code: ");
code = kbd.next();
switch(code){
case "r":
residential = price * 0.07;
cde = false;
total = +residential;
break;
case "m":
multidwelling = price * 0.06;
cde = false;
total = + multidwelling;
break;
case "c":
commercial = price * 0.035;
cde = false;
total = +commercial;
break;
default:
System.out.println("**error**- Property code must be R,M,C");
cde = true;
break;
}
commission=0 + total;
}
}
cde = true;
break;
}
System.out.println("Do u want to calculate another commission(y or n): ");
decision = kbd.next();
switch(decision){
case"y":
yn = true;
break;
case "n":
System.out.println("*********Transacction Summary************");
System.out.println("Total Property Sale: " +prop);
System.out.println("Total Commissions: " + commission);
yn = false;
break;
default :
System.out.println("**Error**Enter valid response");
yesno = true;
while(yesno){
System.out.println("do you want to calculate another commsion(y or n):");
decision = kbd.nextLine();
switch(decision){
case "y":
yn=yesno= true;
break;
case "n":
yn=yesno= false;
break;
}
}
}
}
}
}
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
String code, decision;
int price = 0;
double residential, commercial, multidwelling;
boolean yesno = true;
boolean repeat = true;
boolean cde = true;
double total = 0;
boolean yn = true;
double prop = 0;
double commission = 0;
System.out.println("Real-estate Commission Calculator");
System.out.println("----------------------------------");
while (yn)
{
while (repeat)
{
System.out.print("Enter property's selling price: ");
price = kbd.nextInt();
if (price <= 0)
{
System.out.println("**error**selling price must be greater than zero ");
repeat = true;
}
else
{
prop = prop + price;
while (cde)
{
System.out.println("residential R\nmulti-dwelling M\nCommercial C");
System.out.println("Enter property code: ");
code = kbd.next();
switch (code)
{
case "r":
residential = price * 0.07;
cde = false;
total = +residential;
break;
case "m":
multidwelling = price * 0.06;
cde = false;
total = +multidwelling;
break;
case "c":
commercial = price * 0.035;
cde = false;
total = +commercial;
break;
default:
System.out.println("**error**- Property code must be R,M,C");
cde = true;
break;
}
commission = commission + total;
}
}
cde = true;
break;
}
System.out.println("Do u want to calculate another commission(y or n): ");
decision = kbd.next();
switch (decision)
{
case "y":
yn = true;
break;
case "n":
System.out.println("*********Transacction Summary************");
System.out.println("Total Property Sale: " + prop);
System.out.println("Total Commissions: " + commission);
yn = false;
break;
default:
System.out.println("**Error**Enter valid response");
yesno = true;
while (yesno)
{
System.out.println("do you want to calculate another commsion(y or n):");
decision = kbd.nextLine();
switch (decision)
{
case "y":
yn = yesno = true;
break;
case "n":
yn = yesno = false;
break;
}
}
}
}
kbd.close();
}
}
Hope this solves your problem.

I really need help putting in another variable (Java) For handling the bottom 3 cases:

import javax.swing.JOptionPane;
import java.text.DecimalFormat;
public class CandleLine
{
public static void main(String[] args)
{
double dollars, answer;
int shipmentCode;
dollars = getPrice();
shipmentCode = getCode();
answer = getTotalPrice(dollars,shipmentCode);
output(answer,dollars);
finish();
}
public static double getPrice()
{
double price = 0.0;
boolean done = false;
while (!done)
{
String answer = JOptionPane.showInputDialog(null,"Enter the original price\n(do not use commas or dollar signs)\n or click Cancel to exit:");
if (answer == null) finish();
try
{
price = Double.parseDouble(answer);
if (price <= 0) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Your entry was not in the proper format.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return price;
}
public static int getCode()
{
int code = 0;
boolean done = false;
while (!done)
{
try
{
String message = "Enter the shipment code:" + "\n\n1) Priority\n2) Express\n3) Standard\n\n";
code = Integer.parseInt(JOptionPane.showInputDialog(null,message));
if (code<1 || code>3) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null,"Please enter a 1, 2, or 3.","Error",JOptionPane.INFORMATION_MESSAGE);
}
}
return code;
}
public static double getTotalPrice(double price, int shipmentcode)
{
double totalprice = 0.0;
switch(shipmentcode)
{
case 1:
totalprice = 14.95 + price;
break;
case 2:
totalprice = 11.95 + price;
break;
case 3:
totalprice = 5.95 + price;
break;
}
return totalprice;
}
public static void output(double totalprice, double price)
{
DecimalFormat twoDigits = new DecimalFormat("$#.00");
JOptionPane.showMessageDialog(null,"Your shipment fee is" + shipmentcode,"Shipment Fee",JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(null,"Your total cost is" + twoDigits.format(totalprice),"Price Total",JOptionPane.INFORMATION_MESSAGE);
}
public static void finish()
{
System.exit(0);
}
}
.
.
.
.
.
.
.
.
.
The case 3 needs to be zero when it total price exceeds $75 (no shipping cost over that price). How do I implement this?
case 3:
if (price > 75 ) {
totalPrice = price;
} else {
totalprice = 5.95 + price;
}
break;
So in total, how many possibilities are there for the shipping cost of an order?
final double [] shipmentprice = {14.95, 11.95, 5.95};
public static double getTotalPrice (final double price, final int shipmentcode)
{
return price + shipmentprice[shipmentcode -1];
}
A shorter code, but not very object oriented. I'm not sure whether I see an Enum rising. :)

Categories