Java while loop doesn't work as intended - java

public static void main(String[] args) {
boolean run = true;
while (run) {
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to MetricMan - the best converter in town!");
System.out.println("Choose and option:");
System.out.println("A) Fahrenheit to Celsius");
System.out.println("B) Celcius to Fahrenheit");
System.out.println("C) Miles to Kilometers");
System.out.println("D) Kilometers to Miles");
System.out.println("E) Inches to Centimeters");
System.out.println("F) Centimeters to Inches");
System.out.println("X) Quit the program");
System.out.print("Your choice > ");
String choice = kb.nextLine();
double output; int input;
System.out.print("Enter the number of ");
switch (choice) { // do actions according to the user's choice. convert and display
case "A":
System.out.print("Farenheit > ");
input = kb.nextInt();
output = convertFtoC(input);
System.out.println(input+" farenheit is "+output+" celsius");
break;
case "B":
System.out.print("Celsius > ");
input = kb.nextInt();
output = convertCtoF(input);
System.out.println(input+" celsius is "+output+" farenheit");
break;
case "C":
System.out.print("miles > ");
input = kb.nextInt();
output = convertMtoK(input);
System.out.println(input+" miles is "+output+" kilometres");
break;
case "D":
System.out.print("kilometres > ");
input = kb.nextInt();
output = convertKtoM(input);
System.out.println(input+" kilometres is "+output+" miles");
break;
case "E":
System.out.print("inches > ");
input = kb.nextInt();
output = convertItoC(input);
System.out.println(input+" inches is "+output+" centimeters");
break;
case "F":
System.out.print("centimeters > ");
input = kb.nextInt();
output = convertCtoI(input);
System.out.println(input+" centimeters is "+output+" inches");
break;
case "X":
System.out.println(); System.out.println();
System.out.println("May the odds be ever metric!");
run = false;
break;
}
System.out.println();
kb.nextLine();
}
} // end of main()
there's my main method. As seen in the code, when X has been entered the code should stop running straight away, however its actual output is
...
Your choice > X
Enter the number of
May the odds be ever metric!
there is a "enter the number of " before the actualy intended output and I see no reason for it to be there. Can anyone help fix this?

You are doing System.out.print("Enter the number of "); in every case .So thats why its printing when you entered X so try to put System.out.print("Enter the number of "); inside if(check if string entered is not X) like below
if(!choice.equals("X")){
System.out.print("Enter the number of ");
}
OR
put System.out.print("Enter the number of "); inside each switch case where you want it as pointed by #Tanmoy

That line occurs every time you go through the loop. One way to fix this is to make that call in each case statement except for X.

In your code
System.out.print("Enter the number of ");
switch (choice) { // do actions according to the user's choice. convert and display
so you are basically printing this before switch, so the output is expected, you may want to call inside cases rather outside switch, when its x, just quit.

Related

How to Create a looping Menu in Java?

I am new to Java and learning. I am making a looping menu in Java. But when I select "a" and enter the details it doesn't go back to the menu.
I have done a bit of research and I need to add a Do and While loop here, but I'm confused on how to implement that here. A bit of guidance is extremely appreciated
Heres my code below:
switch(selection) {
case 'A':
case 'a':
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 'B':
case 'b':
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 'x':
case 'X':
System.out.println("Exiting data entry menu..");
break;
//equivalent to an else
default:
System.out.println("ERROR! - Please Enter a Valid Selection!");
}
while(selection != 'X');
Is this what you needed?
char selection;
do
{
do
{
//Menu
System.out.println("Toll Road Data Entry Menu");
System.out.println("-----------------------------------------");
System.out.println("A - Record Trip");
System.out.println("B - Record Breakdown Incident");
System.out.println("X - Exit");
System.out.print("Enter Your Selection: ");
selection = input.nextChar();
if (selection!='a' || selection!='A' || selection!='b' || selection!='B' || selection!='x' || selection!='X')
{
System.out.println("Selection must be a single character, A,B or X");
continue;
}
else
break;
} while (1);
switch(selection)
{
case 'A':
case 'a':
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 'B':
case 'b':
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 'x':
case 'X':
System.out.println("Exiting data entry menu..");
break;
//equivalent to an else
default:
System.out.println("ERROR! - Please Enter a Valid Selection!");
}
} while(selection != 'X');
I usually through them in while loops that way it just through me back to main menu when done
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
boolean menu=true;
int selection,sector_break;
String date,enter_point,exit_point,
breakdown;
double rec_cost;
while(true)
{
System.out.print(String.format("\033[2J"));
System.out.print("Your Menu Title \n\n");
System.out.print("1. Selection A\n");
System.out.print("2. Selection B\n");
System.out.print("3. Selection C\n");
System.out.print("4. Selection D\n");
System.out.print("5. Exit Menu D\n");
selection = Integer.parseInt(input.nextLine());
if(selection<1 || selection>4)
return;
switch(selection){
case 1:
System.out.print("Enter a Trip Date: ");
date = input.nextLine();
System.out.print("Enter Trip Point: ");
enter_point = input.nextLine();
System.out.print("Enter Exit Point: ");
exit_point = input.nextLine();
break;
case 2:
System.out.print("Enter Breakdown Date: ");
breakdown = input.nextLine();
System.out.print("Enter Sector Breakdown Occured in: ");
sector_break = input.nextInt();
System.out.print("Enter Vehicle Recovery Cost: ");
rec_cost = input.nextDouble();
break;
case 3:
// your code here
default:
// your code here
}
}
}
}

Force the user to pick option 1 before option 2

I want to force the user to select choice 1 before they can proceed and select choice 2 any help would appreciated.
(note I've only done if,switch,while,for,do....while,methods and arrays in java so far)
Scanner sc = new Scanner(System.in);
int[] ages = new int[3];
int choice;
do {
System.out.println("Average Age program");
System.out.println("Enter 1 to enter ages");
System.out.println("Enter 2 to calculate the average Age");
System.out.println("Enter 0 to Exit");
choice = sc.nextInt();
switch(choice) {
case 1:
acceptAges(ages);
break;
case 2:
averageAge(ages);
break;
default:
System.out.print("invalid option");
}
} while(choice != 0);
}
You could simply not display choice 2 until 1 was chosen at least once.
Scanner sc = new Scanner(System.in);
int[] ages = new int[3];
int choice;
boolean is2Enabled=false,
do{
System.out.println("Average Age program");
System.out.println("Enter 1 to enter ages");
if(is2Enabled)
System.out.println("Enter 2 to calculate the average Age");
System.out.println("Enter 0 to Exit");
choice=sc.nextInt();
switch(choice)
{
case 1:
acceptAges(ages);
is2Enabled=true;
break;
case 2:
if(is2Enabled)
averageAge(ages);
else
System.out.print("invalid option");
break;
default:
System.out.print("invalid option");
}
}while(choice != 0);
}

Program breaks from switch java

for some reason, when I enter '1' on the switch menu, nothing happens, but the program doesn't terminate. It's the same with options 2-5. The default option works just fine. Can anyone help me with this? Thanks
Code:
import java.util.Scanner;
public class ConversionTrial {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
menu: while(true) {
System.out.println("Please choose an option:");
System.out.println("1. Enter values");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
choice = input.nextInt();
switch(choice){
case -1:
case 6:
break menu;
case 1:
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange:");
break;
case 2:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in Euros are" + poundEuro);
case 3:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in Dollars are" + poundDollars);
case 4:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in Yen are" + poundYen);
case 5:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in Rupees are" + poundRupees);
default:
System.out.println("You must enter an option between 1 and 6!");
}
}
input.close();
exchange.close();
}
}
First, don't create two scanner objects. Just create the one, and use that.
Second, in you options 1-5, you are waiting for input before outputting anything to the user, so that is likely why it seems to not be working. You should add a prompt for the value expected.
Third, you are missing break; at the end of cases 2-5.
Fourth, using a label is generally not the best way to do things. It can end up with some hard to read code. A better way would be to do it would be to have a flag variable, boolean exit = false;. Then, your while loop will loop based on it not being true, while(!exit). And in your case 6:, exit = true;
Fifth, why do you have -1 exit, when it isn't an option given the user? I would remove that.
import java.util.Scanner;
public class ConversionTrial{
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int choice;
Scanner input = new Scanner(System.in);
boolean exit = false;
while(!exit) {
System.out.println("Please choose an option:");
System.out.println("1. Enter values");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
choice = input.nextInt();
switch(choice){
case 6:
exit = true;
break;
case 1:
System.out.print("Please enter your values you would like to exchange: ");
pound = input.nextDouble();
break;
case 2:
System.out.print("Please enter your values you would like to exchange: ");
pound = input.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in Euros are " + poundEuro);
break;
case 3:
System.out.print("Please enter your values you would like to exchange: ");
pound = input.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in Dollars are " + poundDollars);
break;
case 4:
System.out.print("Please enter your values you would like to exchange: ");
pound = input.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in Yen are " + poundYen);
break;
case 5:
System.out.print("Please enter your values you would like to exchange: ");
pound = input.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in Rupees are " + poundRupees);
break;
default:
System.out.println("You must enter an option between 1 and 6!");
break;
}
}
input.close();
}
}
Edit: As a bonus, I also noticed that option 1 doesn't actually do anything. Is that intentional? And for cleaner code, I would initialize the values of your conversion variables when you define the variables, instead of each time they are used. You could also use those values in your menu, so they only need to be changed once if the values change.
The menu label is'nt really necessary. Get rid of it, that is bad code smell.
Additionally you miss the break; in all other cases.
Add breaks for every case to exit the switch statement. Not sure if this is the answer you wanted, so let me know if you are looking for something else.
It's like PeterMmm said. You forget the break; in your cases.
Your code is working but i think it does not what u want it to do.
If i press 1 i can type in a double and afterwards it tells me i can type in a value.
But with this value from switch 1 happens just nothing.
The other options i can type in a double and get the exchange in a foreign currency.
What are u planning to do?
just ran your code and I have figured out what you want to do. I am getting the following:
> Please enter your values you would like to exchange:Please choose an
> option:
> 1. Enter values
> 2. Euros (1GBP = 1.28EUR)
> 3. Dollars (1GBP = 1.51USD)
> 4. Yen (1GBP = 179.80JPY)
> 5. Rupees (1GBP = 95.60INR)
> 6. Exit 2
> 1.2 Your amounts in Euros are1.536
But pay attention that you must enter double values.
Also, I insist that you use break to exit the switch for every case existing in your switch.
Regards
When you select an option 1-5, the program then waits for another double (the amount you want to convert), only then does it respond. So select an option, then give it another double value and it should tell you the conversion amount
import java.util.Scanner;
public class ConversionTrial {
public static void main(String[] args) {
double pound;
double euro;
double dollars;
double yen;
double rupees;
double poundEuro;
double poundDollars;
double poundYen;
double poundRupees;
int choice;
Scanner input = new Scanner(System.in);
Scanner exchange = new Scanner(System.in);
menu: while(true) {
System.out.println("Please choose an option:");
System.out.println("1. Enter values");
System.out.println("2. Euros (1GBP = 1.28EUR)");
System.out.println("3. Dollars (1GBP = 1.51USD)");
System.out.println("4. Yen (1GBP = 179.80JPY)");
System.out.println("5. Rupees (1GBP = 95.60INR)");
System.out.println("6. Exit");
choice = input.nextInt();
switch(choice){
case 1:
pound = exchange.nextDouble();
System.out.print("Please enter your values you would like to exchange:");
break;
case 2:
pound = exchange.nextDouble();
euro = 1.28;
poundEuro = pound * euro;
System.out.println("Your amounts in Euros are" + poundEuro);
break;
case 3:
pound = exchange.nextDouble();
dollars = 1.51;
poundDollars = pound * dollars;
System.out.println("Your amounts in Dollars are" + poundDollars);
break;
case 4:
pound = exchange.nextDouble();
yen = 1.28;
poundYen = pound * yen;
System.out.println("Your amounts in Yen are" + poundYen);
break;
case 5:
pound = exchange.nextDouble();
rupees = 1.28;
poundRupees = pound * rupees;
System.out.println("Your amounts in Rupees are" + poundRupees);
break;
case -1:
case 6:
break menu;
default:
System.out.println("You must enter an option between 1 and 6!");
}
}
input.close();
exchange.close();
}
}

When I run my program i get the error java.lang.StringIndexOutOfBoundsException: String index out of range: 0

here is my code
import java.io.*;
import java.util.*;
public class weightOnOtherPlanets {
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine( );
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " " ;
switch(p){
case 'A':
case 'a':
System.out.println(answerPhrase +(.091*weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720*weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865*weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612*weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
}
I have used almost the exact same code for another similar practice project and it worked just fine. When i run the program it goes to the point where it asks for a weight input, then it displays the choice list, but with the error message exception in "main":
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at weightOnOtherPlanets.main(weightOnOtherPlanets.java:14)
I don't know why it gives this error before allowing keyboard input for String choice.
This is because of the way Scanner scans lines.
After you enter a double (the weight), you press Return. This tells System.in to take all the characters you entered and pass them to the scanner. The scanner then reads the part that interests it - the double number - but leaves everything else waiting for the next operation.
This means the Return you pressed - the end-of-line - is still there. Now, the next thing is nextLine(). The scanner sees it, and it reads all the characters it has until it finds an end-of-line. But as we said, the end-of-line is right there. So it reads that, and gives you all the characters it found before it. Which is none at all, because there were no other characters between the double number and the end-of-line.
This means you get an empty string. And an empty string doesn't have a character at position 0, because that would mean it was not empty.
So what you should do is, after receiving the double, you should add a kbReader.nextLine(); - just like that, without putting the value anywhere. This will skip the end-of-line you entered for the double, and then you'll get the next line properly.
When you do your menu reading, though, you should be checking that the string is not empty before you call charAt(0). After all, the user can decide to press Return rather than make a valid choice. So your system should either ignore that or tell him that it's not a legal input, rather than fail with an exception.
You call nextDouble(); and after that you call nextLine() to get your answer phrase. But that call to nextLine(); will only consume the rest of the line on which you entered your double and it will be empty, therefore choice.charAt(0); will throw an exception.
Try doing something like this to consume the rest of the line and then call the nextLine() to get the answer phrase.
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
kbReader.nextLine(); // Consume the rest of the line
// ...
String choice = kbReader.nextLine(); // Get the actual input
char p = choice.charAt(0);
try this:
public static void main(String[] args) {
Scanner kbReader = new Scanner(System.in);
System.out.println("Enter your weight");
double weight = kbReader.nextDouble();
System.out.println("choose a planet by entering the corresponging letter\n");
System.out.println("A. Voltar");
System.out.println("B. Krypton");
System.out.println("C. Fertos");
System.out.println("D Servantos");
String choice = kbReader.nextLine();
if (choice.isEmpty()) {
choice = kbReader.nextLine();
}
char p = choice.charAt(0);
String answerPhrase = "Your weight is " + " ";
switch (p) {
case 'A':
case 'a':
System.out.println(answerPhrase + (.091 * weight));
break;
case 'B':
case 'b':
System.out.println(answerPhrase + (.720 * weight));
break;
case 'C':
case 'c':
System.out.println(answerPhrase + (.865 * weight));
break;
case 'D':
case 'd':
System.out.println(answerPhrase + (4.612 * weight));
break;
default:
System.out.println("Please enter either A,B,C,or D");
break;
}
}
You need to read for input differently. That's why you are throwing an exception.
char p = choice.charAt(0); // why not just do a string comparison instead?
is where the error comes up. This is because choice is null / has no charAt(0).
Irregardless I would use something like this instead
char p = ''
while(in.hasNext()) {
String input = in.nextLine();
if (p.length()>0){
p = choice.charAt(0);
}
//do whatever you wanted to with p
This should give you the behavior you are looking for.
Don't forget to consider changing the double input to work roughly the same though.

Java scanner not returning multiple word variable

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.

Categories