Java switch statement not working properly - java

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;
}

Related

Basic Menu with Cases

I am creating a basic banking app that tracks a user's bank account activities, and I cannot seem to figure out why when I run my code that it is simply running what I have set for the "default" case; so even when I press 1,2,3, or 4, the console states, "Error -- Please choose a valid option."
Thanks in advance!
package Account;
import java.util.Scanner;
public class Account extends Bank {
int Balance;
int Previoustransaction;
int amount;
int amount2;
String Name;
String ID;
Account(String Name,String ID){
}
void deposit(int amount) {
if (amount != 0) {
Balance+=amount;
Previoustransaction=amount;
}
}
void withdraw(int amount) {
if(amount!=0) {
Balance-=amount;
Previoustransaction = -amount;
}
}
void getPrevioustransaction() {
if(Previoustransaction > 0) {
System.out.println("Deposited:" + Previoustransaction);
}
else if(Previoustransaction<0) {
System.out.println("Withdrawn:" + Math.abs(Previoustransaction));
} else {
System.out.println("No transaction occurred.");
}
}
void Menu() {
int choice = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Welcome," + Name + ".");
System.out.println("Your account number is" + ID);
System.out.println("What would you like to do?");
System.out.println("1.Check balance.");
System.out.println("2. Make a deposit.");
System.out.println("3. Make a withrawl.");
System.out.println("4. Show last transaction.");
System.out.println("0. Exit.");
do {
System.out.println("Choose an option.");
choice = scan.nextInt();
System.out.println();
switch(choice) {
case'1':
System.out.println("Balance = $" + Balance);
System.out.println();
break;
case'2':
System.out.println("Enter an amount to deposit.");
int amount = scan.nextInt();
deposit (amount);
System.out.println();
break;
case'3':
System.out.println("Enter an amount to withdrawl.");
int amount2 = scan.nextInt();
withdraw(amount2);
break;
case '4':
getPrevioustransaction();
break;
case '0':
break;
default:
System.out.println("Error -- Please choose a valid option.");
}
} while (choice != 0);
System.out.println("Thank you for using the Bank Account Tracker!");
scan.close();
}
{
}
{
}
}
The reason your program isn't working as you expect is that:
you are prompting for user input
capturing that input as a numeric value; specifically, primitive data type int
comparing that int input against various character values – that is, values of primitive data type ch (such as '1')
Here's a paired down version of what you're doing:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case '1':
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
Here's that same block, but instead of case '1' (which matches on a single character value), I changed it to case 1 (which matches on an integer value):
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch (choice) {
case 1: // <-- this is the only edit, use 1 instead of '1'
System.out.println("match");
break;
default:
System.out.println("some other input found: " + choice);
}
So, to fix your program, change your various case statements to use integer values, not characters.

How do I convert this if-else statement into a switch statement in java?

The prompt is:
Convert the following if-else-if statement into a switch statement. Don’t rewrite the constants or variable definitions, just the if statement.
final char BLT = 'b';
final char VEGAN = 'v';
final char TUNA = 't';
final char ROAST_BEEF = 'r';
double price;
int sandwichType;
System.out.println("Enter sandwich type: ");
sandwichType = keyboard.nextLine().charAt(0);
if (sandwichType == VEGAN || sandwichType == TUNA) {
price = 3.99;
} else if (sandwichType == BLT) {
price = 4.19;
} else if (sandwichType == ROAST_BEEF) {
price = 4.99;
} else {
System.out.println("That's not a valid sandwich type.");
System.exit(0); // This ends the program
}
System.out.println("Your total is is $" + (price*1.0825));
My current code is this:
switch (sandwichType) {
case 1:System.out.println("The price is $" + (3.99*1.0825));
case 2: System.out.println("The price is $" + (4.19*1.0825));
case 3: System.out.println("The price is $" + (4.99*1.0825));
break;
You are forgetting breaks in between the switch cases. You also will want to use the char names of the different sandwiches instead of numbers. Finally, if none of the cases match the given sandwhichType, you'll want to have a default case, this would be essentially be your else statement from the previous code. The one tricky piece is the first case which accepts two different types which can be done by having a case followed by another case.
switch (sandwhichType)
{
case VEGAN:
case TUNA:
price = 3.99;
break;
case BLT:
price = 4.19;
break;
case ROAST_BEEF:
price = 4.99;
break;
default:
System.out.println("That's not a valid sandwich type.");
System.exit(0);
break;
}
System.out.println("Your total is is $" + (price*1.0825));
The cases should be options
case BLT:
You also need a default case
default:
break;
And break; after every case.

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

nested switch case error with wrong output?

I am experiencing some problems with the output of my program. I am certain the error is logical but i just cant fix it. error should be somewhere around here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
I don't know how to fix it. At the moment if i insert A+ to the program it would give me the result for A-. Heres my full code.
public class SwitchCase {
public static void main(String[] args) {
System.out.println("Please enter your grade (ex.A+) to get the mark range");
/*This block of codes converts from string to
* char and it gets the plus or minus sign
*/
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
/*This is my utility scanner,
* I created char grade to get the user input.
*/
java.util.Scanner input=new java.util.Scanner(System.in);
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
/*This set of code contains the nested switch statements
* that i will use to output the correct mark range
* to the user. It also contains a try statement to find runtime
* errors in the program.
*/
try{
switch(grade)
{
case 'A':
switch(modifier)
{
case '+': System.out.println("Your grade is 90-99.99%"); break;
case '-': System.out.println("Your grade is 80-84.99%"); break;
default: System.out.println("Your grade is 85-89.99%"); break;
}
break;
case 'B':
switch(modifier)
{
case'+': System.out.println("Your grade is 77.00 - 79.99%"); break;
case'-': System.out.println("Your grade is 70.00 - 72.99%"); break;
default: System.out.println("Your grade is 73.00 - 76.99%"); break;
}
break;
case 'C':
switch(modifier)
{
case'+': System.out.println("Your grade range is 67.00 - 69.99%"); break;
case'-': System.out.println("Your grade range is 60.00 - 62.99%"); break;
default: System.out.println("Your grade range is 63.00 - 66.99%"); break;
}
break;
case 'D':
switch(modifier)
{
case'+': System.out.println("Your grade range is 55.00 - 59.99%"); break;
case'-': System.out.println("-"); break;
default: System.out.println("Your grade range is 50.00 - 54.99%"); break;
}
break;
case 'F':
switch(modifier)
{
default: System.out.println("Your grade range is 0.00-49.99%"); break;
}
break;
}
}
catch (java.util.InputMismatchException e) { //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid grade!");
}
input.close(); //ends the user input
}
}
After
char grade = userInputString.charAt(0);
add
char modifier = ' ';
if( userInputString.length() > 1 ){
modifier = userInputString.charAt(1);
}
and remove the code dealing with plusorminus.
You should also add some code to avoid hiccups after reading the input line.
userInputString = userInputString.trim(); // maybe user hits space?
if( ! userInputString.matches( "^[A-F][-+]?$" ) ){
// error message...
}
Not sure whether there is E, and F+ or F-?? We have different grades. Perhaps the regex should be
"^[A-E][-+]?|F$"
You might be inserting
A+
but you're only consuming the A.
String userInputString = input.nextLine();
char grade = userInputString.charAt(0);
The modifier is assigned, deterministically, here
String plusorminus ="+-";
char mark = plusorminus.charAt(0);
char modifier = 0;
if(plusorminus.length() >= 1)
{
modifier = plusorminus.charAt(1);
}
The length of plusorminus will always be 2 which means that modifier will always be plusorminus.charAt(1), ie. -. You want to assign the second character of your input string as the modifier.

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