how to add item in java POS - java

String item1="Burger";
String item2="Softdrink";
int burger_price=40, sofdrink_price=20;
int x=0;
while(x==0){
System.out.println("Select item [1] burger [2] sofdrink");
int select=scan.nextInt();
switch(select){
case 1:
System.out.println("Enter Quantity: ");
int qty=scan.nextInt();
int total=qty*burger_price;
System.out.println("Item: Burger");
System.out.println("Quanity: "+qty);
System.out.println("Total: "+total);
x=1;
break;
case 2:
System.out.println("Enter Quantity: ");
int qty2=scan.nextInt();
int total2=qty2*sofdrink_price;
System.out.println("Item: Softdrink");
System.out.println("Quanity: "+qty2);
System.out.println("Total: "+total2);
x=1;
break;
default: System.out.println("Select [1] and [2] only");
}
}//end while`

MadProgrammer gave a really great explanation. I just put it together as a code. I tried to make minimum changes to your original code so that you understand better.
import java.util.Scanner;
public class BugerCheese {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int burger_price=40, sofdrink_price=20;
int qty1=0, qty2=0;
while(true){
System.out.println("Select item [1] burger [2] sofdrink");
int select=scan.nextInt();
switch(select){
case 1:
System.out.println("Enter Quantity: ");
qty1 += scan.nextInt();
break;
case 2:
System.out.println("Enter Quantity: ");
qty2 += scan.nextInt();
break;
default: System.out.println("Select [1] and [2] only");
}
System.out.println("Enter 9 to add more items. Enter any other key to calculate total");
if(9!=scan.nextInt()){
break;
}
}
if(qty1>0){
int total=qty1*burger_price;
System.out.println("Item: Burger");
System.out.println("Quanity: "+qty1);
System.out.println("Total: "+total);
}
if(qty2>0){
int total2=qty2*sofdrink_price;
System.out.println("Item: Softdrink");
System.out.println("Quanity: "+qty2);
System.out.println("Total: "+total2);
}
System.out.println("GrandTotal: "+(qty1*burger_price+qty2*sofdrink_price));
}
}

First, you need some kind of loop...
boolean done = false;
do {
//...
} while (!done);
Then you need to provide some way for the user to exit the loop
boolean done = false;
do {
System.out.println("Select item [1] burger [2] sofdrink or [0] when you're done");
//...
switch(select){
case 0:
done = true;
break;
}
} while (!done);
Now, you need someway to keep a running tally of what's been ordered, since you only have two items, you could use two variables...
int burgerCount = 0;
int softDrinkCount = 0;
boolean done = false;
do {
//...
Now you can just increment the counters based on the user selection...
Now, automatically, you need to ask the user for two things, what they want and how much they want, you could simplify the process a bit by been a little clever...
System.out.println("Select item [1] burger [2] sofdrink or [0] when you're done");
int select=scan.nextInt();
scan.nextLine();
switch (select) {
case 0:
done = true;
break;
case 1:
case 2:
System.out.println("Enter Quantity: ");
int qty=scan.nextInt();
scan.nextLine();
switch (select) {
case 1:
burgerCount += qty;
break;
case 1:
softDrinkCount += qty;
break;
}
break;
}
// Show details
Make sure, you call nextLine after you read the nextInt, as there is still a carriage return in the buffer ;)
Then you can display running a tally...
//...
System.out.println("You've ordered...");
double burgerTally = burger_price * burgerCount;
double drinkTally = burger_price * drinkTally;
System.out.println(burgerCount + " burgers # $" + burger_price + " for a sub total of $" + burgerTally);
System.out.println(softDrinkCount + " soft drinks # $" + sofdrink_price + " for a sub total of $" + drinkTally);
System.out.println("For a total of $" + (burgerTally + drinkTally));
} while (!done);
Because of the way the code is laid out, the tally will be displayed regardless of what you pick...
Now, if you have more items, then an array is going to come in very handy and will reduce the over all amount of code you might need...

Related

how do I get back to an outer switch if I am inside an inner switch?

I am trying to program a menu for my calculator. I do not know how to get out of my inner loop and get back to my outer loop once I have executed the inner loop. I have to finish the whole case of the inner loop before I can get back to the outer loop. Is there a way that I can go back and forth of the nested switch whenever I want to? and when I execute my outer switch case 3, it executes infinitely. Maybe because it's inside a loop.
import java.util.Scanner;
public class MainInterface {
static Scanner input = new Scanner(System.in);
static boolean hasRun = false;
public static void main(String args[])
{
Calculator Mycal = new SimpleCalculator();
ScientificCalculator Mycal2 = new ScientificCalculator();
mainMenu();
int choice = input.nextInt();
do {
System.out.println("\n");
switch(choice) // outer switch
{
case 1: simpleCalculatorMenu();
int choice2 = input.nextInt();
switch(choice2) // inner switch
{
case 1: //ADDITION
System.out.println("ADDITION");
System.out.println("\n");
System.out.println("Enter first number: ");
float x = input.nextFloat();
System.out.println("Enter second number: ");
float y = input.nextFloat();
System.out.println("\n");
System.out.println("The sum of " + x + " " + y + " is " + Mycal.add(x, y));
System.out.println("\n");
System.out.println("Would you like to return to the main menu?");
System.out.println("\n");
System.out.println("Enter 1. to return 2. to exit");
choice = input.nextInt();
break;
}
break;
case 2: System.out.println("SCIENTIFIC CALCULATOR");
System.out.println("\n");
System.out.println("1. power(x, pow) 2. sin(xDeg) 3. cos(xDeg) 4. tan(xDeg)");
System.out.println("\n");
System.out.println("5. pi() 6. fact(x) ");
int choice3 = input.nextInt();
switch(choice3) {
case 1:
System.out.println("POWER");
System.out.println("\n");
System.out.println("Enter first number: ");
double x = input.nextDouble();
System.out.println("Enter second number: ");
double y = input.nextDouble();
System.out.println("\n");
System.out.println("The power of " + x + " to the power of " + y + " is " + Mycal2.power(x, y));
System.out.println("\n");
System.out.println("Would you like to return to the main menu?");
System.out.println("\n");
System.out.println("Enter 1. to return 2. to exit");
choice = input.nextInt();
break;
case 2:
}
break;
case 3: mainMenu();
break;
case 4: System.exit(choice);
break;
}
} while(choice != 0);
}
public static void simpleCalculatorMenu () {
System.out.println("SIMPLE CALCULATOR");
System.out.println("\n");
System.out.println("1. Addition 2. Subtraction 3. Multiplication 4. Division");
System.out.println("\n");
System.out.println("5. Squared Root 6. Squared 7. Cube 8. Discount ");
}
public static void mainMenu () {
System.out.println("What calculator do you want to use?");
System.out.println("\n");
System.out.println("1. Simple Calculator \t 2. Scientific Calculator");
}
}
by adding label you can try like this
OUTER:
switch(condition1) {
case x:
switch(condition2) {
case y:
System.out.println("hello");
break OUTER;
}
}

(JAVA) do while loop for my vending machine

this project i use do while loop with switch case to check the input case is not match or not. i run the code but the result not what i wanted. what i expect is if the user type the wrong case, the do while loop will loop back to the input where user need to enter the case.
here is the code
package vending.machine;
import java.util.Scanner;
import java.util.*;
import java.util.ArrayList;
import static vending.machine.adddrinks.drinksList;
public class VendingMachine {
public static void main (String []args){
Scanner sc= new Scanner(System.in);
double money;
double total;
double balance;
do{
System.out.println("\nPlease insert money:");
money = sc.nextDouble();
if(money < 1.2){
System.out.println("Not enough money");
}
}while(money < 1.2);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
System.out.print("Select: 1 or 2 or 3 or 4\n");
int select=sc.nextInt();
do{
switch(select){
case 1:{
total = adddrinks.drinksList.get(0).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 2:{
total = adddrinks.drinksList.get(1).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 3:{
total = adddrinks.drinksList.get(2).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
case 4:{
total = adddrinks.drinksList.get(3).getdrinkPrice();
balance = money - total;
System.out.println("Here is your balance: " + balance);
break;
}
default:{
System.out.println("Invalid");
break;
}
}
}while(select<5);
}
}
here is the result
enter image description here
From what I understood from your code. When you are giving the input as 5 it is giving invalid.
After that it will go to the while statement and check the condition there. If you are inside the switch case and select any random case It will show you invalid. After that depending upon the number that you have entered.
If the number is less than 5, It will again go to switch case.
As it doesn't make sense as If you continue to provide correct input to it. The code will continue to execute making the balance going in the negative. this condition should be changed to
while(balance>1.2)
assuming that it is minimum amount that is necessary to buy a drink. This will check the condition after every drink and will hopefully do what you were hoping.
On side Note : Make your code modular.
You need to loop over your input, i was so free to improve your code a bit (sorry I do not like repetations):
private static void main10(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
int select = 0;
double balance = 0;
boolean running = true;
while (running) {
if (sc.hasNextInt()) {
select = sc.nextInt();
if (0 < select && select <= adddrinks.drinksList.size()) {
double price = adddrinks.drinksList.get(select - 1).getdrinkPrice();
if (balance < price) {
System.out.println("Not enough money, " + select + " costs " + price);
} else {
balance -= price;
System.out.println("You choosed " + select + " , you will find it in the dispenser");
}
} else {
System.out.println("Invalid input, please retry");
}
} else if (sc.hasNextDouble()) {
balance += sc.nextDouble();
} else {
String input = sc.next();
if (input == "q") {
running = false;
if (0 < balance)
System.out.println("please don't forget your change with amount of: " + balance);
System.out.println("Have a nice day, happy to see you again");
break;
} else if (input == "h") {
System.out.println("What drinks are you looking for");
adddrinks.showDrinks();
adddrinks.viewDrinks();
} else {
System.out.println("Invalid input, please retry");
}
}
System.out.println("Your balance is: " + balance);
System.out.println(
"please chouce your product (e.g 2), enter coins (e.g 2.0), click on 'h' to show product list or click on 'q' to get your change");
}
}

writing java program with repeated main menu

I've spent hours on this program trying to figure out how to repeat the main menu to show until the user write 3 (to quit the program).
The program asks the user to enter 2 integer numbers, then Main menu shows to choose from 3 options.
I chose the do while loop to force it show at least once, but i don't know what's my mistake?
package javaapplication33;
import static java.lang.System.exit;
import java.util.Scanner;
public class JavaApplication33 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter two numbers: ");
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn = showMenu();
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
}
public static int showMenu() {
int optionn = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Main Menu:");
System.out.println("--------------");
System.out.println("1.Add the numbers");
System.out.println("2.Multiply the numbers");
System.out.println("3.Quit");
System.out.println("--------------");
System.out.println("Enter your choice:");
optionn = keyboard.nextInt();
return optionn;
}
You could consider just a while loop, instead of a do-while.
int optionn = 0;
while (optionn != 3)
{
optionn = showMenu();
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}
}
Additionally, there's no reason to clear out your optionn variable in your showMenu method.
try this
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
int optionn = showMenu();//SHOWS THE MENU AGAIN
} while (optionn == 3);
System.out.println("Thank you. Good Bye.");
Your showmenu() method isnt in your while that why i dosent repeat
The two lines of code that needed fixing - have comments, see below:
do {
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
exit(0);
default:
System.out.println("Sorry, please enter valid Option");
}// End of switch statement
optionn = showMenu(); // <--- changed
} while (optionn != 3); // <--- changed
A couple of mistakes.
First you should be getting the user input inside the do/while loop. Just move your optionn=showMenu() inside the do (That way you can show the options again and allow the user to choose again).
Second you want to keep on looping while optionn!=3 instead of optionn==3 (You want to continue looping if the user doesn't want to exit).
I would also not use exit(0) and also move your exit print statement to inside the loop (So you print it before you exit your function). Something like this:
int n1 = input.nextInt();
int n2 = input.nextInt();
int multb = n1 * n2;
int optionn;
do {
optionn = showMenu(); //Allow user to select from menu every iteration
switch (optionn) {
case 1:
int sum = n1 + n2;
System.out.println(sum);
break;
case 2:
System.out.println(n1 + "*" + n2 + " = " + multb);
break;
case 3:
System.out.println("Thank you. Good Bye."); //Moved from the bottom
return; //I would use return instead of the exit(0) here.
//exit(0);
default:
System.out.println("Sorry, please enter valid Option");
showMenu();
}// End of switch statement
} while (optionn != 3); //Make sure this is != not ==
Hope this helps!

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
}

The switch just continues

I am doing a simple project just to keep myself a bit fresh. Decided to do a Vending Machine. well I to the end and test it. It does case 1 and 2 just fine but when I get to case 3 it either finishes out the entire program when i select a snack option or if i change it to a if/else in case 3 it will just stop running when i select a snack. Why is it doing this? what can i do to fix it?
import java.util.Scanner;
public class Vending
{
public static void main(String[] args)
{
int choice;
double deposit = 0;
double total = 0;
Scanner keyboard = new Scanner(System.in);
boolean test = true;
do
{
System.out.println("\nVending Machine Menu");
System.out.println("\n \n1. View Items");
System.out.println("2. Put Money into Machine");
System.out.println("3. Select an Item");
System.out.println("4.Recieve Change");
System.out.println("5.Exit");
System.out.println("\nPlease Make a Selection: ");
choice = keyboard.nextInt();
switch(choice)
{
case 1 :
System.out.println("\n 1. Fizzy soda : $0.50 \n 2. Gummi Possums : $0.25"
+ "\n 3. Doggy Bones : $0.25 \n 4. Fruity Punch : $0.50");
System.out.println("Press ENTER to continue");
try{System.in.read();}
catch(Exception e){}
break;
case 2:
System.out.println("Enter amount to deposit: ");
deposit = keyboard.nextDouble();
total = total + deposit;
break;
case 3:
Scanner keypad = new Scanner(System.in);
System.out.println("\n 1. Fizzy soda : $0.50 \n 2. Gummi Possums : $0.25"
+ "\n 3. Doggy Bones : $0.25 \n 4. Fruity Punch : $0.50");
System.out.println("\nSelect an item: ");
int snack = keypad.nextInt();
if (total > 0)
{
if(snack == 1)
{
if (total >= .5)
{
System.out.println("The Vending Machine dispenses a FIZZY SODA");
total = total - .5;
}
else
{
System.out.println("Deposit more money");
}
}
else if(snack == 2)
{
if (total >= .25)
{
System.out.println("The Vending Machine dispenses a package of GUMMI POSSUMS");
total = total - .25;
}
else
{
System.out.println("Deposit more money");
}
}
else if(snack == 3)
{
if(total >= .25)
{
System.out.println("The Vending Machine Dispenses a package of DOGGY BONES");
total = total - .25;
}
else
{
System.out.println("Deposit more money");
}
}
else if(snack == 4)
{
if(total >= .5)
{
System.out.println("The Vending Machine Dispenses a can of FRUITY PUNCH");
total = total - .5;
}
else
{
System.out.println("Deposit more money");
}
}
}
else
{
System.out.println("Please deposit some money");
}
keypad.close();
case 4:
System.out.println("You recieve " + total + " in change from the Vending Machine");
total = 0;
case 5:
System.exit(0);
}
}
while (test == true);
keyboard.close();
}
}
You need to use break at the end of a case statement if you do no want to execute the next case statement :
case 3:
// do something
break; // break to avoid executing case 4
case 4:
// ...
if you are relying on the break; to get out of cases then you have no break statement in case 3, 4 or 5.
At first glance: Your cases 3 and 4 have no break statement at the end.
You forget to add break keyword at the end your cases, break will prevent executing the next case.
The switch-case should look like this template:
case 1:
// do something
break;
case 2:
// do something
break;
default:
// do something
break;
So Add break at the end of each case such as:
case 4:
System.out.println("You recieve " + total + " in change from the Vending Machine");
total = 0;
break;
Read more about switch-case in java.

Categories