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.");
**/
}
}
Related
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");
}
}
Hi guys i am having an issue with how to do this, i have googled it but its not making much sense.
i need to do this;
The program asks the user if they wish to continue.
If Yes is selected, it will return to the Main menu.
If No is selected, Total Amount Payable will be
displayed and then the program will terminate
int option, quantity, confirm;
float childTotal;
float adultTotal;
float seniorTotal;
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
char resume;
Scanner input = new Scanner(System.in);
System.out.println("1 = Child (4-6 yrs)");
System.out.println("2 = Adult (16+ yrs)");
System.out.println("3 = Senior (60+ yrs)" + "\n");
System.out.println("Enter your option:" );
option=input.nextInt();
switch (option) {
case 1:
System.out.println("Enter total No of tickets for Child:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " child tickets");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
case 2:
System.out.println("Enter total No of tickets for Adult:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " adult tickets");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
default:
System.out.println("Enter total No of tickets for Senior:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " senior tickets");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
}
if (confirm !=1) {
System.out.println("Incorrect key! User to go back to main menu");
}
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
} else {
switch (option) {
case 1:
childTotal=(int) ((double) quantity*childCost) ;
System.out.println("Total amount for child tickets: $" + childTotal);
break;
case 2:
adultTotal=(int) ((double) quantity*adultCost) ;
System.out.println("Total amount for adult tickets $" + adultTotal);
break;
default:
seniorTotal=(int) ((double) quantity*seniorCost);
System.out.println("Total amount for senior tickets $" + seniorTotal);
break;
}
}
Create a Boolean variable set as true.
boolean continueLoop = true;
Add your main logic into a while loop until continue is true
while(continueLoop){
//Do your code here
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y'){}
else{
//Do Code here
continueLoop=false;
}
} //End while loop.
After the while loop continue with your code. I have changed the condition of resume == y to resume !=y because if the user does not press y the code should stop iterating.
Your code would become
int option, quantity, confirm;
float childTotal;
float adultTotal;
float seniorTotal;
final double childCost = 18;
final double adultCost = 36;
final double seniorCost = 32.50;
boolean continueLoop = true;
char resume;
Scanner input = new Scanner(System.in);
while(continueLoop){
System.out.println("1 = Child (4-6 yrs)");
System.out.println("2 = Adult (16+ yrs)");
System.out.println("3 = Senior (60+ yrs)" + "\n");
System.out.println("Enter your option:" );
option=input.nextInt();
switch (option) {
case 1:
System.out.println("Enter total No of tickets for Child:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " child tickets");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
case 2:
System.out.println("Enter total No of tickets for Adult:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " adult tickets");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
default:
System.out.println("Enter total No of tickets for Senior:" );
quantity=input.nextInt();
System.out.println("You are purchasing " + quantity + " senior tickets");
System.out.println("Press 1 to confirm");
confirm=input.nextInt();
break;
}
if (confirm !=1) {
System.out.println("Incorrect key! User to go back to main menu");
}
System.out.println("Do you wish to continue? (Y/N) ");
resume = input.next().charAt(0);
if (resume == 'y' || resume == 'Y') {
}else{
continueLoop = false;
switch (option) {
case 1:
childTotal=(int) ((double) quantity*childCost) ;
System.out.println("Total amount for child tickets: $" + childTotal);
break;
case 2:
adultTotal=(int) ((double) quantity*adultCost) ;
System.out.println("Total amount for adult tickets $" + adultTotal);
break;
default:
seniorTotal=(int) ((double) quantity*seniorCost);
System.out.println("Total amount for senior tickets $" + seniorTotal);
break;
}
}
}
}
I'm trying to print out different variables I've already declared in different switch cases, they're all in one switch block in a for loop but the compiler isn't allowing me use the variables. Giving me a "cannot find symbol" error.
Here's the code:
public static void main(String[] args) {
double hammer = 3.25, nails = 5.25, paint = 4.75, paintBrush = 2.25, balance = 50.00;
Scanner input = new Scanner(System.in);
System.out.println("Local Hardware Point of Sales");
System.out.println("\t::MENU::");
System.out.println("1. Purchase Items\n2. Display current purchases\n3. Display account balance\n4. Complete transactions and Exit");
System.out.print("Enter choice: ");
int choice = input.nextInt();
switch(choice){
case 1:
for(int i = 0; i <= 2; i++){
System.out.println("\n\tPurchase Items");
System.out.println("What items would you like to purchase?");
System.out.println("\tItems \t\tPrices");
System.out.println("\tHammer\t\t-$3.25\n\tNails\t\t-$3.25\n\tPaint\t\t-$3.25\n\tPaint Brush\t-$3.25");
String item = input.next();
switch (item) {
case "Hammer":
case "hammer":
System.out.println("How many Hammers would you like to purchase?");
int hItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double hPrice = hItem*hammer;
System.out.println("Cost for " + hItem + " Hammers: $" + hPrice);
double hBalance = balance - hPrice;
System.out.println("Final Balance: $" + hBalance);
if(hBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ hItem+ " Hammers (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+hItem+"Hammers for "+ hPrice);
}
}
break;
case "Nails":
case "nails":
System.out.println("How many Nails would you like to purchase?");
int nItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double nPrice = nItem*nails;
System.out.println("Cost for " + nItem + " Nails: $" + nPrice);
double nBalance = balance - nPrice;
System.out.println("Final Balance: $" + nBalance);
if(nBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ nItem+ " Nails (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+nItem+" Nails for "+ nPrice);
}
}
break;
case "Paint":
case "paint":
System.out.println("How many Paints would you like to purchase?");
int pItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double pPrice = pItem*nails;
System.out.println("Cost for " + pItem + " Paints: $" + pPrice);
double pBalance = balance - pPrice;
System.out.println("Final Balance: $" + pBalance);
if(pBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ pItem+ " Paints (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+pItem+" Paints for "+ pPrice);
}
}
break;
case "Paint Brush":
case "paint brush":
System.out.println("How many Paint Brushes would you like to purchase?");
int pbItem = input.nextInt();
System.out.println("Starting Balance: $" + balance);
double pbPrice = pbItem*nails;
System.out.println("Cost for " + pbItem + " Paint Brushes: $" + pbPrice);
double pbBalance = balance - pbPrice;
System.out.println("Final Balance: $" + pbBalance);
if(pbBalance > 50.00){
System.out.println("WARNING: YOU HAVE INSUFFICIENT FUNDS FOR THIS PURCHASE. YOU CANNOT PURCHASE 30 NAILS.");
System.out.println("You will be returned to the main menu...");
}
else{
System.out.println("\nPurchase the "+ pbItem+ " Paint Brushes (Y/N)");
String ch = input.next();
if(ch.equals("Yes") || (ch.equals("Y")) || (ch.equals("y")) ){
System.out.println("You purchased "+pbItem+" Paint Brushes for "+ pbPrice);
}
}
break;
default:
break;
}
System.out.println("\nMake another purchase? (Y/N)");
String ans = input.next();
if(ans.equals("n"))
System.out.println("\tCurrent Receipt");
System.out.println("Items \t\tQuantity \t\tPrice Per \t\tTotal Price");
System.out.println("Hammer \t\t"+**hItem**+" \t\t\t"+hammer+" \t\t\t"+**hPrice**);
System.out.println("Nails \t\t"+**nItem**+" \t\t\t"+nails+" \t\t\t"+**nPrice**);
System.out.println("Paint \t\t"+**pItem**+" \t\t\t"+paint+" \t\t\t"+**pPrice**);
System.out.println("Paint Brush \t\t"+**pbItem**+" \t\t\t"+paintBrush+" \t\t\t"+**pbPrice**);
}
}
}
}
I bolded the variables that are giving the error. P.s I am not allowed to use methods for this project, strictly conditional statements and loops.
Also if anyone doesn't mind, I'm trying to get string input for "Paint Brush" but using input.next() has issues with the space, and when I used input.nexLine() it completely ignored the input and ended the program, so had to revert back to next().
Please if anyone can help, much appreciated. Thanks alot
Declare the variables that give you an error outside of the switch-case. Currently their scope is limited to only the inside of the case part, meaning that for the rest of the code (outside of the case) they don't exist.
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.
This section of my code is not working as I need it to. I need to Select from the menu either A, B, or X and then input a small sentence for the description (multiple) a figure for the cost. I can input all the data perfectly and it returns to the menu (only exiting once inputing X). But the return string for the variable damageDesc is only grabbing the first word prior to the space. I've tried this all night and still can't get it to return all words in the string. Here's the code if anyone can help. Thanks!
do {
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
menuOption = console.next().charAt(0);
switch (menuOption) {
case 'A':
case 'a':
System.out.print("Enter description of damage repair: ");
damageDesc = console.next();
console.nextLine();
System.out.print("Enter repair cost: ");
damageCost= console.nextDouble();
//Place damage description and cost on seperate lines
damageDescFinal = String.format(damageDescFinal + "- %s ($%.2f ) \n", damageDesc, damageCost);
//Also could have used the below
//damageDescFinal = (damageDescFinal+"- "+damageDesc+
// " ($"+damageCost+")"+"\n");
//All damage costs added together
damageCostFinal = damageCostFinal + damageCost;
System.out.println();
break;
case 'B':
case 'b':
System.out.print("Enter details of traffic infringement: ");
fineDesc = console.next();
console.nextLine();
System.out.print("Enter traffic fine amount: ");
fineCost = console.nextDouble();
//Set fine description and cost on seperate lines
fineDescFinal = String.format(fineDescFinal + "- %s ($%.2f ) \n", fineDesc, fineCost);
//Also could have used the below
//fineDescFinal = fineDescFinal+"- "+fineDesc+
// " ($"+fineCost+")"+"\n";
//All fine costs added together
fineCostFinal = fineCostFinal + fineCost;
System.out.println();
break;
case 'X':
case 'x':
//Exit the damage and fine menu
System.out.print("Exiting data entry menu..."+"\n");
System.out.println();
break;
default:
//Error handling for invalid input
System.out.print("***ERROR*** Invalid Selection!"+"\n");
System.out.println();
break;
}
} while (menuOption != 'X' && menuOption != 'x');
Perhaps, you need to use nextLine() for reading the entire line instead of next
Fixed this myself by changing the Double values to strings and then converted them back to a double after the inputs were finished. This solved the scanner problems I was having. Here's the final code that worked:
do {
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
menuOption = console.next().charAt(0);
//Switch to allow either upper or lower case menuOption
switch (menuOption) {
case 'A':
case 'a':
System.out.print("Enter description of damage repair: ");
//Clear scanner
console.nextLine();
//Input damage description
damageDesc = console.nextLine();
System.out.print("Enter repair cost: ");
//Input damage cost
damageCost= console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleDamageCost = Double.parseDouble(damageCost);
//Set damage description and cost on seperate lines for each input
damageDescFinal = String.format(damageDescFinal + "- %s ($%.2f ) \n", damageDesc, doubleDamageCost);
//Concatenate all fine costs for a final value
damageCostFinal = damageCostFinal + doubleDamageCost;
System.out.println();
break;
case 'B':
case 'b':
System.out.print("Enter details of traffic infringement: ");
//Clear scanner
console.nextLine();
//Input fine description
fineDesc = console.nextLine();
System.out.print("Enter traffic fine amount: ");
//Input fine cost
fineCost = console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleFineCost = Double.parseDouble(fineCost);
//Set fine description and cost on seperate lines for each input
fineDescFinal = String.format(fineDescFinal + "- %s ($%.2f ) \n", fineDesc, doubleFineCost);
//Concatenate all fine costs for a final value
fineCostFinal = fineCostFinal + doubleFineCost;
System.out.println();
break;
case 'X':
case 'x':
//Exit the damage and fine menu
System.out.print("Exiting data entry menu..."+"\n");
System.out.println();
break;
default:
//Error handling for invalid input
System.out.print("***ERROR*** Invalid Selection!"+"\n");
System.out.println();
break;
}
//Exits menu loop and allow code to continue
} while (menuOption != 'X' && menuOption != 'x');
why not in this case use .ToLowerCase or .ToUperCase? this way you can get a cleaner code
do {
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
Scanner console = new Scanner(System.in);
menuOption = console.next().toLowerCase().charAt(0);
//Switch to allow either upper or lower case menuOption
switch (menuOption) {
case 'a':
System.out.print("Enter description of damage repair: ");
//Clear scanner
console.nextLine();
//Input damage description
damageDesc = console.nextLine();
System.out.print("Enter repair cost: ");
//Input damage cost
damageCost= console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleDamageCost = Double.parseDouble(damageCost);
//Set damage description and cost on seperate lines for each input
damageDescFinal = String.format(damageDescFinal + "- %s ($%.2f ) \n", damageDesc, doubleDamageCost);
//Concatenate all fine costs for a final value
damageCostFinal = damageCostFinal + doubleDamageCost;
System.out.println();
break;
case 'b':
System.out.print("Enter details of traffic infringement: ");
//Clear scanner
console.nextLine();
//Input fine description
fineDesc = console.nextLine();
System.out.print("Enter traffic fine amount: ");
//Input fine cost
fineCost = console.nextLine();
//Convert string fineCost back to a double
//This was input as a String as scanner produces an error
double doubleFineCost = Double.parseDouble(fineCost);
//Set fine description and cost on seperate lines for each input
fineDescFinal = String.format(fineDescFinal + "- %s ($%.2f ) \n", fineDesc, doubleFineCost);
//Concatenate all fine costs for a final value
fineCostFinal = fineCostFinal + doubleFineCost;
System.out.println();
break;
case 'x':
//Exit the damage and fine menu
System.out.print("Exiting data entry menu..."+"\n");
System.out.println();
break;
default:
//Error handling for invalid input
System.out.print("***ERROR*** Invalid Selection!"+"\n");
System.out.println();
break;
}
//Exits menu loop and allow code to continue
} while (menuOption != 'x');
but you should do more classes like
Public void menu(){
System.out.println("Damage Repair / Traffic Infringement Data Entry "+
"Menu");
System.out.println("-------------------------------------------------"+
"---");
System.out.println();
System.out.println("A - Record Damage Repair Details");
System.out.println("B - Record Traffic Infringement Details");
System.out.println("X - Exit");
System.out.println();
System.out.print("Enter your selection (A/B/X):");
}
and so on, to get a more organized and clean code. segementation is your best friend.