The switch just continues - java

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.

Related

(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");
}
}

Java do while loop won't loop- Java (All int)

Code for menu options won't loop, but has no errors. I intentionally wrote it similar to my while loop that loops just fine. I have to use only integers, and my instructor did tell me to turn my inputs into variables. Most of it isn't quite finished but I'm working on that at the same time as trying to figure all this out.
//Loop to check user input
num=-1;
while (num<0)
{
//Getting user entered interger
System.out.print("Please enter a positive number: ");
num = kb.nextInt();
//Ensuring positive interger
if (num >= 0)
{
System.out.println("You've entered the number " + num + ".");
}
else
{
System.out.println("Error! The number you've entered is not a valid interger.");
}
}
copy = num;
//Printing menu loop
copy2 = -1;
do
{
//Menu making
System.out.println(" ");
System.out.println("1. Enter a new number.");
System.out.println("2. Print the number of odd digits, even digits, and zeros in the interger.");
System.out.println("3. print if the number is light or heavy.");
System.out.println("4. Print the prime numbers between 2 and the interger (inclusive).");
System.out.println("5. Quit the program.");
System.out.println(" ");
System.out.print("Please enter your menu choice: ");
choice = kb.nextInt();
copy2 =choice;
//Checking entry
if (0<copy2 && copy2<=5)
{
System.out.println("You chose option " +copy2+".");
}
//Option one
if (copy2 == 1)
{
System.out.print("Will work on soon.");
}
//Option two
if (copy2 == 2)
{
oddNum=0;
evenNum=0;
zero=0;
while (copy>0)
{
if (copy %10==0)
{
zero++;
}
else if (copy %2==1)
{
evenNum++;
}
else
{
oddNum++;
}
}
copy = copy/10;
System.out.println("Even numbers: " + evenNum+
"\nOdd numbers: "+ oddNum +
"\nZeros: " +zero );
}
//Option three
if (copy2 == 3)
{
loh = 0;
do
{
System.out.println("To check if your number is light or heavy, we need a second interger.");
System.out.print("Please enter a second positive interger: ");
loh = kb.nextInt();
if (loh >= 0)
{
numWeight = ((loh +copy)/2);
//Test num weight
System.out.println("Check: " +numWeight);
if (numWeight > copy)
{
System.out.print("The number " + copy + " compared to the number "
+ loh + " is a heavy number.");
}
else
{
System.out.print("The number " + copy + " compared to the number "
+ loh + " is a light number.");
}
}
if (loh < 0)
{
System.out.println("Error! The number you've entered is not a valid interger.");
}
}while (loh <=0);
}
//Option four
if (copy2 ==4)
{
primeNumbers = 0;
for (int i=1; i<=copy; i++)
{
int counter = 0;
for(int prime = i; prime>=1; prime--)
{
if (i%prime==0)
{
counter = counter +1;
}
}
if (counter==2)
{
primeNumbers = primeNumbers + i;
}
}
System.out.println("Prime numbers from 2-"+copy+" are: ");
System.out.println(primeNumbers);
}
//Option five
else
{
System.out.print("Error! Please enter a valid menu option.");
}
}while (copy2 <0 && copy2 >=6);
}//End main
}//End class
You should use switch case for your purpose. nested if/else isn't good idea for menu options but switch case make it more clear to understand what are you going to do.
switch (num) {
case c1:
statements // they are executed if variable == c1
System.out.println("1. Enter a new number.");
break;
case c2:
System.out.println("2. Print the number of odd digits, even digits, and zeros in the interger.");
statements // they are executed if variable == c2
break;
case c3:
case c4:
statements // they are executed if variable == any of the above c's
break;
. . .
default:
statements // they are executed if none of the above case is satisfied
break;
}

Java switch statement not working properly

I have two classes for calculating the cost of an ISP plan and gathering input/displaying the cost. ISPMain.java and ISP.java ISPMain is supposed to display service plans and ask the user to select their plan by the letter of the package, like package a, package b, or package c. I have it set up so the user inputs the character to choose the plan. If the plan is the not package c (unlimited plan) the user is prompted to enter the hours they used.
Once the hours are entered and stored in hoursUsed, ISP.java calculates the cost and then ISPMain.java displays it. My problem is that my switch statement in ISP only is displaying the default value and I am not sure why. Can anyone explain?
public class ISPMain
{
public static void main(String[] args)
{
char pkg;
double hoursUsed;
Scanner kb = new Scanner(System.in);
System.out.println("The three packages offered are: ");
System.out.println("Package A: For $9.95 per month, 10 hours of access are provided. \nAdditional hours are $2.00 per hour.");
System.out.println("Package B: For $14.95 per month, 20 hours of access are provided. \nAdditional hours are $1.00 per hour.");
System.out.println("Package C: For $19.95 per month, unlimited access is provided.");
System.out.println("Please type the letter of the package you have: ");
pkg = kb.nextLine().toUpperCase().charAt(0);
if(pkg == 'A')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'B')
{
System.out.print("Enter number of hours: ");
hoursUsed = kb.nextDouble();
}
else if(pkg == 'C')
{
System.out.print("You have unlimited access! No need to enter hours used. \n");
}
ISP user = new ISP();
System.out.print("Total charges: " + user.calculateCharges());
}
}
switch statement from ISP.java:
public double calculateCharges()
{
switch (pkg)
{
case 'A':
if (hoursUsed < 10)
{
return 9.95;
}
else
{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20)
{
return 14.95;
}
else
{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}
}
to conclude, my if else works fine, but the switch only displays "Invalid input"
As others have said, you need to get the pkg variable into the scope of your switch statement. Try this:
public double calculateCharges(char pkg){
switch(pkg){
case('A'):{
//insert code here
break;
}
case('B'):{
//insert code here
break;
}
case('C'):{
//insert more code here
break;
}
default:{
//code here
break;
}
}
}
Then call your method like:
System.out.print("Total charges: " + user.calculateCharges(pkg));
The default: case statement will always run in your code because char pkg isn't defined as a parameter for your method.
The user may enter A, B, or C, but since it does not get passed the end result will always be default, therefore causing your Invalid input.
Try :
public double calculateCharges(char pkg){
switch (pkg)
{
case 'A':
if (hoursUsed < 10){
return 9.95;
}else{
return (hoursUsed - 10)*2 + 9.95;
}
case 'B':
if (hoursUsed < 20){
return 14.95;
}else{
return (hoursUsed - 20) + 14.95;
}
case 'C':
return 19.95;
default:
System.out.println("Invalid input!");
return 0;
}

how to add item in java POS

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...

Use switch statement after if statement

I want to use switch statement after an if statement but I can't and I don't know what is the problem.
public class main {
public static void main (String[] args) {
String input; //To hold user's input.
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //other variables
//Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Prompt the user to select a Internet Package.
System.out.print("Which package did you purchase? ( Enter the Package's letter)");
input = keyboard.nextLine();
selectPackage = input.charAt(0);
System.out.print("Please select the amount of hours used.");
input = keyboard.nextLine();
hourUsage = Double.parseDouble(input);
//Display pricing for selected package...
switch (selectPackage)
{
case 'a':
case 'A':
if (hourUsage > 10)
{
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" +
totalCharges + " per month. ");
}
else
System.out.println("Your total is $9.95 per month.");
break;
case 'b':
case 'B':
if (hourUsage > 20 )
{
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else
System.out.println("Your total is $13.95 per month.");
break;
case 'c':
case 'C':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice. Choice A,B,C");
}
}
}
System.out.println("Your total is $19.95 per month.");
}
else
System.out.println("Your total is $19.95 per month.");
}
}
Now I want to use the switch statement for telling user that if he/she chose package "B", he would save 20 dollars.
I have had a look through your code and have made ALOT of edits and improvements, the main issue I found was your use of } in the wrong places. I believe this was because you haven't organised your code very well; in future consider organising your code to make it easier to find errors, below I have corrected your code and have put the last few lines into a comment as I'm not sure why you have them there, if there are any questions about it, just ask me:
public class Test {
public static void main(String[] args) {
char selectPackage; //To hold Internet Package
double hourUsage, totalCharges, addCharges; //other variables
//Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Prompt the user to select a Internet Package.
System.out.print("Which package did you purchase? ( Enter the Package's letter)");
char input = keyboard.next().charAt(0);
selectPackage = Character.toUpperCase(input);
System.out.print("Please select the amount of hours used.");
hourUsage = keyboard.nextDouble();
//Display pricing for selected package...
switch (selectPackage) {
case 'A':
if (hourUsage > 10) {
addCharges = hourUsage - 10;
totalCharges = (addCharges * 2.0) + 9.95;
System.out.println("You have used " + hourUsage + " hours and your total is $" + totalCharges + " per month. ");
}
else {
System.out.println("Your total is $9.95 per month.");
}
break;
case 'B':
if (hourUsage > 20 ) {
addCharges = hourUsage - 20;
totalCharges = (addCharges * 1.0) + 13.95;
System.out.println("You have used " + hourUsage + " and your total is $" + totalCharges + " per month.");
}
else{
System.out.println("Your total is $13.95 per month.");
}
break;
case 'C':
System.out.println("Your total is $19.95 per month.");
break;
default:
System.out.println("Invalid Choice. Choice A,B,C");
}
/**System.out.println("Your total is $19.95 per month.");
System.out.println("Your total is $19.95 per month.");
**/
}
}

Categories