Breaking a while loop by case in Java - java

I need to issue break a while loop if a case is matched in a switch statement. The case is as follows: if a user enters either a number less than zero or anything greater than five. I have the switch working most of my cost except the two exceptions Ive mentioned. Here is my code:
import java.util.Scanner;
public class Product
{
public static void main(String args[])
{
int cntr = 0;
int product = 0;
int units = 0;
double totalcost = 0;
Scanner MK = new Scanner(System.in);
cntr=0;
while (cntr >= 0 && cntr <=5)
{
System.out.println("Enter Product no.(1-5) or -1 to Quit");
product = MK.nextInt();
switch(product) {
case 1:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 2.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 2:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.50;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 3:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 9.98;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 4:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 4.49;
totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
cntr++;
}
break;
case 5:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
product = MK.nextInt();
double cost = 6.87;
totalcost = totalcost + (cost*product);
System.out.println("Current total cost: " + totalcost);
cntr++;
}
case 6:
{
System.out.println("Product " + (cntr+1));
System.out.println("Enter Quantity or -1 to Quit");
//product = MK.nextInt();
//double cost = 2.98;
//totalcost = totalcost + cost*product;
System.out.println("Current total cost: " + totalcost);
//cntr++;
}
break;
}
System.out.println("Total cost-->" +totalcost);
}
}
}
If anyone can point me in the right direction on how to stop my program when anything less than zero or greater than 5 is entered I would really appreciate it.

A couple of options:
Use a flag that you set when you want the loop to end (in your default or -1 clause), or
Use a labelled statement and a directed break in your default (or -1) clause
In this specific situation where you said you want the entire program to end, you could use System.exit
Here's more about option 2:
label: while (...) { // <== Labelled statement
switch (...) {
case ...:
// ...
break; // <=== Normal (undirected) break, just exits what
// it's in (switch in this case)
// ...
default:
break label; // <=== Directed break, exits loop
}
}
It's also handy for nested loops.
Side note: There's no need for the { and } you have surrounding the statements in your case clauses. The code for case continues until the break. (Yes, it's a bit different from other statements.)
Side note 2: You've said Enter Product no.(1-5) or -1 to Quit in your prompt, but you have cases for the values 1 to 6 (inclusive). You probably meant Enter Product no.(1-**6**) or -1 to Quit.

Related

How to make a loop for this script?

I am working on a simple/scientific calculator in java, and I am having trouble putting this in a while loop so the user can continuously use the calculator. I've tried putting it in different places in the code, but it either repeats the input section or doesn't repeat anything. Any tips? Here is my code below:
static Scanner s1 = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to my calculator:");
String operator = "";
Scanner op = new Scanner(System.in);
System.out.println("Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.");
operator = op.nextLine();
if (operator.equals("1")) {
System.out.println(standard());
}
if (operator.equals("2")) {
System.out.println(scientific());
}
if (operator.equals("QUIT")) {
System.out.print("System quit");
}
}
public static int standard() {
//The system will print 0 at the end to show that it's working
System.out.println("Standard Calculator chosen.");
System.out.println("Type 1 if you wish to use addition, 2 for subtraction, 3 for multiplication, 4 for exponent, 5 for division, or 6 for mod.");
int input2 = s1.nextInt();
int num1 = 0;
int num2 = 0;
//String loop = "";
switch (input2) {
case 1:
System.out.println("(Add chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Addition - (" + num1 + "+" + num2 + ") = " + addExact(num1, num2));
break;
case 2:
System.out.println("(Sub chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Subtration - (" + num1 + "-" + num2 + ") = " + subtractExact(num1, num2));
break;
case 3:
System.out.println("(Multi chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Multiplication - (" + num1 + "*" + num2 + ") = " + multiplyExact(num1, num2));
break;
case 4:
System.out.println("(Exp chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the exponent: ");
num2 = s1.nextInt();
System.out.println("Exponent - (" + num1 + "^" + num2 + ") = " + Math.pow(num1, num2));
break;
case 5:
System.out.println("(Div chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Division - (" + num1 + "/" + num2 + ") = " + floorDiv(num1, num2));
break;
case 6:
System.out.println("(Mod chosen) Please enter the first value: ");
num1 = s1.nextInt();
System.out.println("Please enter the second value: ");
num2 = s1.nextInt();
System.out.println("Mod - (" + num1 + "%" + num2 + ") = " + floorMod(num1, num2));
break;
}
return (0);
}
public static double scientific() {
//The system will print 0.0 at the end to show that it's working
System.out.println("Scientific Calculator chosen.");
System.out.println("Type 1 for sin, 2 for cos, 3 for tan, 4 for floor, 5 for ceil, 6 for square root, 7 for cube root, 8 for rounding, 9 for min, 10 for max.");
int input2 = s1.nextInt();
double val1 = 0.0;
double val2 = 0.0;
switch (input2) {
case 1:
System.out.println("(Sin chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Sin - (" + val1 + ") = " + sin(val1));
break;
case 2:
System.out.println("(Cos chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Cos - (" + val1 + ") = " + cos(val1));
break;
case 3:
System.out.println("(Tan chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Tan - (" + val1 + ") = " + tan(val1));
break;
case 4:
System.out.println("(Floor chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Floor - (" + val1 + ") = " + Math.floor(val1));
break;
case 5:
System.out.println("(Ceil chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Ceil - (" + val1 + ") = " + Math.ceil(val1));
break;
case 6:
System.out.println("(Square root chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Square root - (" + val1 + ") = " + sqrt(val1));
break;
case 7:
System.out.println("(Cube root chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Cube root - (" + val1 + ") = " + cbrt(val1));
break;
case 8:
System.out.println("(Round chosen) Please enter the value :");
val1 = s1.nextDouble();
System.out.println("Round - (" + val1 + ") = " + round(val1));
break;
case 9:
System.out.println("(Min chosen) Please enter the 1st value :");
val1 = s1.nextDouble();
System.out.println("Enter the 2nd value: ");
val2 = s1.nextDouble();
System.out.println("Minimum - (" + val1 + "," + val2 + ") = " + min(val1,val2));
break;
case 10:
System.out.println("(Max chosen) Please enter the 1st value :");
val1 = s1.nextDouble();
System.out.println("Enter the 2nd value: ");
val2 = s1.nextDouble();
System.out.println("Maximum - (" + val1 + "," + val2 + ") = " + max(val1,val2));
break;
}
return val2;
}
}
}
You need to do something as follows, as you want to repeat all the process until the user choose to QUIT the calculator app:
public static void main(String[] args) {
System.out.println("Welcome to my calculator:");
String operator = "";
while (!operator.equals("QUIT")) {
Scanner op = new Scanner(System.in);
System.out.println("Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.");
operator = op.nextLine();
if (operator.equals("1")) {
System.out.println(standard());
}
if (operator.equals("2")) {
System.out.println(scientific());
}
if (operator.equals("QUIT")) {
System.out.print("System quit");
}
}
}
output:
Welcome to my calculator:
Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.
1
Standard Calculator chosen.
Type 1 if you wish to use addition, 2 for subtraction, 3 for multiplication, 4 for exponent, 5 for division, or 6 for mod.
1
(Add chosen) Please enter the first value:
1
Please enter the second value:
2
Addition - (1+2) = 3
0
Type 1 if you wish to use the Standard calculator, 2 for the Scientific calculator, or QUIT if you wish to quit the program.
Here's a solution for your "main" method that:
uses a "while" loop and a boolean value "keepGoing" to decide if it should loop again (or exit)
uses a "switch" statement to handle calling different functions based on input
if "QUIT" input, it sets "keepGoing = false" so that the "while" loop will exit
defines one Scanner, and names it clearly ("scanner")
passes that single Scanner object to the methods which need it (standard and scientific)
Two other changes worth making:
remove the global static Scanner s1 – don't use global variables, it will lead to hard-to-find problems in your code
edit those method signatures to accept a Scanner parameter:
public static int standard(Scanner s1)`
public static double scientific(Scanner s1)
Here's the code:
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to my calculator:");
String prompt = "Type 1 if you wish to use the Standard calculator, " +
"2 for the Scientific calculator, or " +
"QUIT if you wish to quit the program.";
boolean keepGoing = true;
while (keepGoing) {
System.out.println(prompt);
switch (scanner.nextLine()) {
case "1" -> System.out.println(standard(scanner));
case "2" -> System.out.println(scientific(scanner));
case "QUIT" -> {
System.out.print("System quit");
keepGoing = false; // this ejects from the while loop
}
}
}

Combining multiple switch variables into one string

I am to create a program that shows the full receipt (plus all the items included.) However, when two of the same items are selected the output is:
4 Combo price
5 Combo price
Instead of:
9 Combo price
Is it possible to merge the two same switch cases? I've tried a counter and yet it still doesn't work. I don't know what other logic to put behind this.
import java.text.NumberFormat;
import java.util.Scanner;
public class Menu {
public static void main(String args []){
final double COFFEE= 1.8, SOFTDRINK = 2.0;
final double STARTER= 4.0, DESSERT= 3.5;
final double MAIN= 8.0;
final double COMBO1 = 11.0, COMBO2= 11.5, COMBO3 = 15.0;
double sum=0;
int item = 0, quantity=0;
int freeSoftDrink=0, freeCoffee=0;
String order="";
char decide= 'N';
boolean quit= false;
Scanner sc = new Scanner (System.in);
NumberFormat format= NumberFormat.getInstance();
format.setMaximumFractionDigits(2);
format.setMinimumFractionDigits(2);
do{
System.out.println("------------------ MENU ------------------");
System.out.println("ITEM"+"\t\t\t\tPRICE");
System.out.println("1.Coffee"+"\t\t\t"+"RM1.80");
System.out.println("2.Soft Drink"+"\t\t\t"+"RM2.00");
System.out.println("3.Dessert"+"\t\t\t"+"RM3.50");
System.out.println("4.Starter"+"\t\t\t"+"RM4.00");
System.out.println("5.Main Course"+"\t\t\t"+"RM8.00");
System.out.println("6.Main+Dessert"+"\t\t\t"+"RM11.00");
System.out.println("7.Main+Starter"+"\t\t\t"+"RM11.50");
System.out.println("8.Combo(Main+Starter+Dessert)"+"\t"+"RM15.00");
System.out.println("-----------------------------------------");
System.out.print("Select an item: ");
item = sc.nextInt();
if ((item<=8) && (item>=1)){
System.out.print("Enter quantity (1-50): ");
quantity = sc.nextInt();
}
while (((quantity<=0) || (quantity>=51)) && ((item<=8) && (item>=1)))
{
System.out.print("Invalid. Please re-enter quantity: ");
quantity = sc.nextInt();
}//end while
switch(item){
case 1:
System.out.println("You've ordered: "+quantity+" Coffee.\n");
sum=sum+(quantity*COFFEE);
order=order.concat(quantity +" Coffee\t\t\t"+"RM"
+format.format(quantity*COFFEE)+"\n");
break;
case 2:
System.out.println("You've ordered: "+quantity+" Soft Drink.\n");
sum=sum+(quantity*SOFTDRINK);
order=order.concat(quantity+" Soft Drink\t\t\t"+"RM"
+format.format(quantity*SOFTDRINK)+"\n");
break;
case 3:
System.out.println("You've ordered: "+quantity+" Dessert.\n");
sum=sum+(quantity*DESSERT);
order=order.concat(quantity+ " Dessert\t\t\t" +"RM"
+format.format(quantity*DESSERT)+"\n");
break;
case 4:
System.out.println("You've ordered: "+quantity+" Starter.\n");
sum=sum+(quantity*STARTER);
order=order.concat(quantity+" Starter\t\t\t"
+"RM"+format.format(quantity*STARTER)+"\n");
break;
case 5:
System.out.println("You've ordered: "+quantity+" Main.\n");
sum=sum+(quantity*MAIN);
order=order.concat(quantity+" Main\t\t\t\t" + "RM"
+format.format(quantity*MAIN)+"\n");
break;
case 6:
System.out.println("You've ordered: "+quantity+" Main+Dessert.\n");
sum=sum+(quantity*COMBO1);
order=order.concat(quantity+" Main+Dessert\t\t\t"
+"RM"+format.format(quantity*COMBO1)+"\n");
freeCoffee = freeCoffee + quantity;
break;
case 7:
System.out.println("You've ordered: "+quantity+" Main+Starter.\n");
sum=sum+(quantity*COMBO2);
order=order.concat(quantity+" Main+Starter\t\t\t"+"RM"
+format.format(quantity*COMBO2)+"\n");
freeSoftDrink = freeSoftDrink + quantity;
break;
case 8:
System.out.println("You've ordered: "+ quantity+" Combo.\n");
sum=sum+(quantity*COMBO3);
order=order.concat(quantity+" Combo"+" \t\t\t"
+"RM"+format.format(quantity*COMBO3)+"\n");
freeSoftDrink = freeSoftDrink + quantity;
freeCoffee = freeCoffee + quantity;
break;
default:
System.out.println("Invalid item.");
}//end switch
System.out.println("Do you want anything else? [Y/N]");
decide= sc.next().charAt(0);
System.out.println("");
while ((decide!='N' && decide!='n') && (decide!='Y' && decide!='y')){
System.out.print("Invalid. Try again: ");
decide=sc.next().charAt(0);
System.out.println("");
}
if (decide=='N'|| decide =='n'){
quit=true;
}
}//end do
while(!quit);
System.out.println();
System.out.println("Orders");
System.out.println("--------------------------------------------");
System.out.print(order);
if (freeCoffee<=0){
System.out.print("");
}
else {
System.out.println("*free "+ freeCoffee + " coffee.");
}
if (freeCoffee<=0){
System.out.print("");
}
else{
System.out.println("*free "+ freeSoftDrink + " soft drinks.");
}
System.out.println("--------------------------------------------");
System.out.println ("Your total bill\t\t\tRM"+ format.format(sum));
System.out.println("--------------------------------------------");
}//end main
}//end class
The specific line that is causing the issue is:
order=order.concat(quantity+"Main+Dessert\t\t\t"+"RM"+format.format(quantity*COMBO1)+"\n");
Everytime a new COMBO comes in, it appends to the string instead of adding to COMBO cost if one exists already.
A possible fix that I can think of is that you store the state of each item in a HashMap. So your case statement will look something like this:
Map<String, Integer> orderMap = new HashMap<>();
case 6:
System.out.println("You've ordered: "+quantity+" Main+Dessert.\n");
sum=sum+(quantity*COMBO1);
orderMap.containsKey("Combo")
? orderMap.put("Combo", orderMap.get("Combo") + sum) // if the key already exists then we add to the sum otherwise we create a new entry.
: orderpMap.put("Combo", sum);
freeCoffee = freeCoffee + quantity;
break;
And then you can collect all the order values and print them in the receipt:
orderMap.entrySet().forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue);
which will print something like:
Starter: 2
Combo: 9

Total of products entered and total of all products entered using Switch

I am trying to get my output to show the total cost of each item entered and a grand total of the cost of all items, the program runs but when I try to use the end-of-file indicator nothing happens, what am I missing?
package switch1;
import java.util.Scanner;
public class Switch1 {
public static void main(String[] args) {
double total = 0;
int productCounter = 0;
int aProduct = 0;
int bProduct = 0;
int cProduct = 0;
int dProduct = 0;
int eProduct = 0;
Scanner input = new Scanner(System.in);
System.out.printf("%s%n%s%n %s%n %s%n",
"Select your product(1=bread, 2=cheese, 3=meat, 4=msutard, 5=mayo)",
"Type the end-of-file indicator to terminate input:",
"On UNIX/Linux/macOS type <Ctrl> d then press Enter",
"On Windows type <Ctrl> z then press Enter");
while (input.hasNext()) {
int product = input.nextInt();
total += product;
++productCounter;
switch (product) {
case 1:
++aProduct;
break;
case 2:
++bProduct;
break;
case 3:
++cProduct;
break;
case 4:
++dProduct;
break;
case 5:
++eProduct;
break;
}
}
System.out.printf("%nProduct Selection:%n");
if (productCounter != 0) {
double aTotal = (aProduct * 1.89);
double bTotal = (bProduct * 3.99);
double cTotal = (cProduct * 6.99);
double dTotal = (dProduct * 1.99);
double eTotal = (eProduct * 2.99);
total = (((double)aProduct * 1.89) + ((double)bProduct * 3.99) + ((double)cProduct * 6.99) + ((double)dProduct * 1.99) + ((double)eProduct * 2.99));
System.out.printf("You ordered %d gallons of milk totaling: %f%n", aProduct, aTotal);
System.out.printf("You ordered %d loaves of bread totaling: %f%n", bProduct, bTotal);
System.out.printf("You ordered %d packages of cheese totaling: %f%n", cProduct, cTotal);
System.out.printf("You ordered %d pounds of meat totaling: %f%n", dProduct, dTotal);
System.out.printf("You ordered %d bottles of mustard totaling: %f%n", eProduct, eTotal);
System.out.printf("Your total grocery bill is: %d%n", total);
}
else {
System.out.println("No products were entered");
}
}
}
Replace scanner.hasNext with scanner.hasNextLine. If you're on a newline and you hit CTRL-D (linux) or CTRL-Z (Windows), hasNextLine should return false.
Maybe a better question is "how do I find out what am I doing wrong? "
One step would be to warp you code in a try-catch block like:
try {
//the code goes here
}catch(Exception ex) {
ex.printStackTrace();
}
And see the exceptions.
It will indicate a problem in this line
System.out.printf("Your total grocery bill is: %d%n", total);

Java switch results (needing to print the values)

I cannot figure this out, I have created a switch in Java for a user to enter specific details. I have created a print statement inside the case to print the result that has been entered. What I want to happen is for a separate print statement to display the combined details of the values entered (after say a few loops). Any help will be greatly appreciated.
Thanks in advance.
Here is my code
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
}
}
}
You could try adding the option to an arraylist.
List<String> listOfEntries=new ArrayList<String>(); // Add strings like damage repair,etc
//Or you could try
List<Integer> listOfOptions=new ArrayList<Integer>();// Add option here, like 1,2
You can add the user chosen options and at any point of time, you can retreive the options chosen by the user and display the values to the user.
Hope this helps!
This would work:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Setup an exit statement
boolean quit = false;
double dCost=0;
double tCost=0;
StringBuilder dDetail= new StringBuilder("The Damage Details are :" );
StringBuilder tDetail= new StringBuilder("The Traffic details are: " );
while (!quit){
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
//Create switch
if (choiceEntry <1){
System.out.println("Please enter a valid menu command (1-3)");
}
else if (choiceEntry >3){
System.out.println("Please enter a valid menu command (1-3)");
}
double damageCost = 0;
switch (choiceEntry){
case 1: System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append(damageDetail+"\n");
dCost=dCost+damageCost;
break;
case 2: System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append( trafficDetail+"\n");
tCost=tCost+trafficCost;
break;
case 3: quit = true;
System.out.println("Menu entry has been terminated.");
System.out.println("the Total traffic cost is "+tCost);
System.out.println("the Total Damage cost is "+dCost);
System.out.println(tDetail);
System.out.println(dDetail);
break;
}
}
}
Use StringBuilder to append your data. PFB updated code :
import java.util.Scanner;
public class Stage3Check {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Setup an exit statement
boolean quit = false;
StringBuilder sb = new StringBuilder();
outer: while (!quit) {
System.out.println("Enter one of the following commands:");
System.out.println("1 - Damage Repair");
System.out.println("2 - Traffic Infringement");
System.out.println("3 - Exit Menu");
int choiceEntry = Integer.parseInt(input.nextLine());
// Create switch
if (choiceEntry < 1 || choiceEntry > 3)
continue outer;
double damageCost = 0;
switch (choiceEntry) {
case 1:
System.out.print("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.print("Enter the damage cost:");
damageCost = Integer.parseInt(input.nextLine());
sb.append("The damage is: " + damageDetail + "\n");
sb.append("The damage cost is: " + "$" + damageCost + "\n");
break;
case 2:
System.out
.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.print("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
sb.append("The traffic infringement is: " + trafficDetail
+ "\n");
sb.append("The traffic infringement cost is: " + "$"
+ trafficCost + "\n");
break;
default:
quit = true;
System.out.println("Menu entry has been terminated.");
break;
}
}
System.out.println(sb.toString());
}
}
1- The print statement should be placed outside the while loop:
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
2- Declare the damageCost variable globally i.e outside the while loop.
3- Change the statement:
double trafficCost = Integer.parseInt(input.nextLine());
to
damageCost = damageCost + Integer.parseInt(input.nextLine());

How to make the switch statement more accurate?

We were ask to make a program using the switch statement..
Here is my code:
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
So basically, the user will input a certain number and it will have different prices... inside the switch statements.
but if the user inputs a wrong number, it will display an error message and i dont want the user to enter the quantity which will be executed after the switch statement.
we are not allowed to use any methods or functions and i dont want to code repeatedly like this:
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
case 2:
price = 410.00;
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
break;
default:
System.out.println("ERROR: Invalid number!");
break;
}
is there any other way not to use if else, methods, functions or coding repeatedly?
ANY HELP WILL BE APPRECIATED.
You can use a boolean flag and make it false if invalid option is selected.
Then only ask user further if flag is true.
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
boolean flag = true;
switch (optionNumber) {
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
default:
flag = false;
System.out.println("ERROR: Invalid number!");
break;
}
if (flag) {
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
Use as this:
while(!valid option)
//do this stuff
Use a flag and set it to true if the number entered is valid, so it will go to your next instruction; else ask again for input.
Throw an exception
default:
throw new InvalidArgumentException("Invalid number!");
See also InvalidArgumentException vs UnexpectedValueException
You could just remove default from the switch statement and check to see if the price is equal to 0 after the switch statement
double price = 0, totalPrice;
System.out.print("Enter the number of your choice: ");
int optionNumber = Integer.parseInt(kb.readLine());
switch(optionNumber)
{
case 1:
price = 190.00;
break;
case 2:
price = 410.00;
break;
}
if (price == 0)
{
System.out.println("ERROR: Invalid number!");
}
else
{
System.out.print("Enter quantity: ");
int quantity = Integer.parseInt(kb.readLine());
totalPrice = price * quantity;
System.out.print("Total price: " + totalPrice);
}
This keeps you from adding unnecessary variables (like a boolean flag) when you already have one (price) with a default value of 0 that you can check against.

Categories

Resources