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
Related
I've writter a calculator program in Java, after a user is done with work,
I want this to happen:
i'll ask if he wants to do more operations, if yes, the program should return to choice input. If no, break the program.
What lines should I add to the code? This is my calc program:
import java.util.*;
class calc
{
public static void main(String ar[])
{
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice=in.next().charAt(0);
switch(choice)
{
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a=in.nextDouble();
double b=in.nextDouble();
System.out.println("SUM = "+(a+b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c=in.nextDouble();
double d=in.nextDouble();
System.out.println("SUBTRACTING "+d+" FROM "+c+" ... DIFFERENCE = "+(c-d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e=in.nextDouble();
double f=in.nextDouble();
System.out.println("PRODUCT = "+(e*f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g=in.nextDouble();
double h=in.nextDouble();
System.out.println("DIVIDING "+g+" BY "+h+" = "+(g/h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt=in.nextDouble();
System.out.println("SQUARE ROOT OF "+sqrt+" = "+Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base=in.nextDouble();
System.out.println("ENTER POWER, USER");
double power=in.nextDouble();
System.out.println(base+" RAISED TO POWER "+power+" = "+Math.pow(base,power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci=in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = "+Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact=in.nextInt();
int factorial=1;
for(int i=fact; i>=1;i--)
factorial=factorial*i;
System.out.println(fact+"! = "+factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
}
}
while loops are your best bet for this type of problem, just think of a condition which the user can choose to toggle the boolean condition.
for example if the user chooses no on the "continuing of operations" choice, then toggle the boolean to false and exit the while loop to end the program.
You need to wrap the program logic in a loop.
Try using a while loop
public static void main(String args[])
{
boolean doContinue = true;
while(doContinue){
char choice;
Scanner in = new Scanner(System.in);
//program logic
//when the user enters a command to end
// set continue=false
}
}
Maybe put the entire program inside a while loop with a continue to run bool condition which could be set false when they want to quit
You can try the following:
import java.util.*;
class calc {
public static void main(String ar[]) {
char choice;
Scanner in = new Scanner(System.in);
System.out.println("WELCOME TO SHREYDAN'S CALC 1.0");
System.out.println(" ");
boolean loop = true;
while (loop) {
System.out.println("YOU CAN DO THE FOLLOWING:");
System.out.println("+: ADDITION");
System.out.println("-: SUBTRACTION");
System.out.println("*: PRODUCT");
System.out.println("/: QUOTIENT");
System.out.println("#: SQUARE ROOT");
System.out.println("^: POWER");
System.out.println("$: ROUND OFF");
System.out.println("!: FACTORIAL");
System.out.println(" ");
System.out.println("ENTER CHOICE");
choice = in.next().charAt(0);
switch (choice) {
case '+':
System.out.println("ENTER 2 NUMBERS, USER");
double a = in.nextDouble();
double b = in.nextDouble();
System.out.println("SUM = " + (a + b));
break;
case '-':
System.out.println("ENTER 2 NUMBERS, USER");
double c = in.nextDouble();
double d = in.nextDouble();
System.out.println("SUBTRACTING " + d + " FROM " + c + " ... DIFFERENCE = " + (c - d));
break;
case '*':
System.out.println("ENTER 2 NUMBERS, USER");
double e = in.nextDouble();
double f = in.nextDouble();
System.out.println("PRODUCT = " + (e * f));
break;
case '/':
System.out.println("ENTER 2 NUMBERS, USER");
double g = in.nextDouble();
double h = in.nextDouble();
System.out.println("DIVIDING " + g + " BY " + h + " = " + (g / h));
break;
case '#':
System.out.println("ENTER NO. FOR SQAURE ROOT:");
double sqrt = in.nextDouble();
System.out.println("SQUARE ROOT OF " + sqrt + " = " + Math.sqrt(sqrt));
break;
case '^':
System.out.println("ENTER BASE, USER");
double base = in.nextDouble();
System.out.println("ENTER POWER, USER");
double power = in.nextDouble();
System.out.println(base + " RAISED TO POWER " + power + " = " + Math.pow(base, power));
break;
case '$':
System.out.println("ENTER DECIMAL VALUES TO ROUND OFF");
double deci = in.nextDouble();
System.out.println("THE NEAREST ROUND OFF = " + Math.round(deci));
break;
case '!':
System.out.println("ENTER A NO. FOR FACTORIAL:");
int fact = in.nextInt();
int factorial = 1;
for (int i = fact; i >= 1; i--)
factorial = factorial * i;
System.out.println(fact + "! = " + factorial);
break;
default:
System.out.println("WRONG CHOICE USER");
}
System.out.println("Want to calculate more?Y/N");
loop = in.next().charAt(0) == 'Y';
}
}
}
I am just trying to call the methods to the main for each switch when it happens, but i just get the error message everytime i try to call any methods, not trying to return anything. ex. if the user enters a or A i want to call the add method to main
public static void main(String[] args)
{
char character;
Scanner keyboard = new Scanner(System.in);
while (character != 'E' || character != 'e')
{
System.out.println(" A:Addition \n S:Subtraction \n M:Multiplication \n D:Division \n R:Modulus \n E:exit");
switch (character)
{
case 'a':
case 'A':
System.out.println("your choice A");
add();
break;
case 's':
case 'S':
System.out.println("your choice S");
subtraction();
break;
case 'm':
case 'M':
System.out.println("your choice M");
multiplication();
break;
case 'd':
case 'D':
System.out.print("your choice D");
division();
break;
case 'r':
case 'R':
System.out.println("your choice R");
modulus();
break;
default:
System.out.println("Error: please enter a valid letter");
break;
}
}
}
public static void add(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a + b;
System.out.println(a + "plus" + b + "is" + total );
}
public static void subtraction(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a-b;
System.out.println(a + "minus" + b + "is " + total);
}
public static void multiplication(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a*b;
System.out.println(a + "times" + b + "is " + total);
}
public static void division(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total = a/b;
System.out.println(a + "divided" + b + "is " + total);
}
public static void modulus(Scanner keyboard)
{
int a,b;
//get integer 1
System.out.println("enter integer 1");
a = keyboard.nextInt ();
//get integer 2
System.out.println("enter integer 2");
b = keyboard.nextInt();
int total= a%b;
System.out.println(a + "modulus" + b + "is " + total);
System.out.println("The program is terminating");
}
}
you're calling the method but you didn't include an argument
take a look at this.
public static void add(Scanner keyboard)
you have an argument, so you must include an argument when calling this method
so
you must call the method like this.
add(keyboard);
You have defined the method which takes Scanner as argument but you are calling the methods with no args.
All the method you are using are supposed to receive a Scanner object while you pass no argument.
For example you call add(); while it signature is
public static void add(Scanner keyboard)
Which is why you get the error.
Instead, use add(keyboard) and repeat the same for substraction, multiplication, division and modulus methods.
So that your switch would now look like
switch (character) {
case 'a':
case 'A':
System.out.println("your choice A");
add(keyboard);
break;
case 's':
case 'S':
System.out.println("your choice S");
subtraction(keyboard);
break;
case 'm':
case 'M':
System.out.println("your choice M");
multiplication(keyboard);
break;
case 'd':
case 'D':
System.out.print("your choice D");
division(keyboard);
break;
case 'r':
case 'R':
System.out.println("your choice R");
modulus(keyboard);
break;
default:
System.out.println("Error: please enter a valid letter");
break;
}
You are missing the arguments in the method call.
case 'a':
case 'A':
System.out.println("your choice A");
add(keyboard); // Add arguments.
break;
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So I am new to Java and to practice my skills I decided to make a basic calculator. So this is my code:
/*Basic calculator.*/
package calculator;
import java.util.Scanner;
public class no_gui {
public static void main(String[] args) {
System.out.println("What math operation do you want to do?");
System.out.println("1. Addition, 2. Subtraction, 3. Multipilcation, 4. Division");
System.out.println("Enter number to corresponding math operation.");
Scanner calc = new Scanner(System.in);
double choice = calc.nextDouble();
double add1, add2, addAnswer, sub1, sub2, subAnswer, mult1, mult2, multAnswer, div1, div2, divAnswer;
if (choice == 1){
System.out.println("Addition");
System.out.println("Enter first number: ");
add1 = calc.nextDouble();
System.out.println("Enter second number: ");
add2 = calc.nextDouble();
addAnswer = add1 + add2;
System.out.println("Your answer is " + addAnswer);
if(choice == 2){
System.out.println("Subtraction");
System.out.println("Enter first number: ");
sub1 = calc.nextDouble();
System.out.println("Enter second number: ");
sub2 = calc.nextDouble();
subAnswer = sub1 + sub2;
System.out.println("Your answer is " + subAnswer);
if(choice == 3){
System.out.println("Multipilcation");
System.out.println("Enter first number: ");
mult1 = calc.nextDouble();
System.out.println("Enter second number: ");
mult2 = calc.nextDouble();
multAnswer = mult1 + mult2;
System.out.println("Your answer is " + multAnswer);
if(choice == 4){
System.out.println("Divsion");
System.out.println("Enter first number: ");
div1 = calc.nextDouble();
System.out.println("Enter second number: ");
div2 = calc.nextDouble();
divAnswer = div1 + div2;
System.out.println("Your answer is " + divAnswer);
}else{
System.out.println("Re-run to use again.");
}
}
}
}
}
}
Every time I run it and choose addition it'll do what ever is inside the if statement. But when I try subtraction it just prints out 2 and terminates the program. It worked before but today it stopped. I even tried a different method of coding and it still doesn't work.
EDIT: Thanks to everyone who responded. My main issue was resolved. But I also have this issue with switch statements and I forgot to mention that in my main question. Do I have to space everything? Does that cause the problem?
You have nested if clauses. Look at your code and think about it logically.
if (choice == 1) {
//add
if (choice == 2) {
//subtract
}
}
You will never enter subtract or any other option for that matter because the outer choice == 1 will never be true. Use this structure instead.
if (choice == 1) {
//add
}else if (choice == 2) {
//subtract
}
Or better, use switch statment. An example is given below:
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
Example source : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Your problem is that your checks of choice are all nested:
if (choice == 1){
// ...
if(choice == 2){
// ...
if(choice == 3){
// ...
if(choice == 4){
// ...
}else{
System.out.println("Re-run to use again.");
}
}
}
}
If choice is 1, then that block will be executed. If it's not 1, then the blocks that should be executed are all unreachable.
Try re-arranging your program like this instead:
if (choice == 1){
// ...
} else if(choice == 2){
// ...
} else if(choice == 3){
// ...
} else if(choice == 4){
// ...
} else {
System.out.println("Re-run to use again.");
}
Your problem would be self-evident if you clicked "format code" in your IDE...
You have (inappropriately) nested your if blocks, like this:
if (choice == 1) {
// do addition
if (choice == 2) {
// etc
Clearly, if choice is anything other than 1, the corresponding if block(s) will never get entered.
Instead, make the if blocks siblings:
if (choice == 1) {
// do addition
} else if (choice == 2) {
// etc
Because you are not closing your if blocks properly. you should:
if (choice == 1) {
System.out.println("Addition");
System.out.println("Enter first number: ");
add1 = calc.nextDouble();
System.out.println("Enter second number: ");
add2 = calc.nextDouble();
addAnswer = add1 + add2;
System.out.println("Your answer is " + addAnswer);
} else if (choice == 2) {
System.out.println("Subtraction");
System.out.println("Enter first number: ");
sub1 = calc.nextDouble();
System.out.println("Enter second number: ");
sub2 = calc.nextDouble();
subAnswer = sub1 + sub2;
System.out.println("Your answer is " + subAnswer);
} else if (choice == 3) {
System.out.println("Multipilcation");
System.out.println("Enter first number: ");
mult1 = calc.nextDouble();
System.out.println("Enter second number: ");
mult2 = calc.nextDouble();
multAnswer = mult1 + mult2;
System.out.println("Your answer is " + multAnswer);
} else if (choice == 4) {
System.out.println("Divsion");
System.out.println("Enter first number: ");
div1 = calc.nextDouble();
System.out.println("Enter second number: ");
div2 = calc.nextDouble();
divAnswer = div1 + div2;
System.out.println("Your answer is " + divAnswer);
} else {
System.out.println("Re-run to use again.");
}
It is better in this case to use a switch/case:
import java.util.Scanner;
public class no_gui {
public static void main(String[] args) {
Scanner calc = new Scanner(System.in);
//double choice = calc.nextDouble();
int choice = 0;
boolean getOut=false;
double add1, add2, addAnswer, sub1, sub2, subAnswer, mult1, mult2, multAnswer, div1, div2, divAnswer;
while(!getOut)
{
System.out.println("What math operation do you want to do?");
System.out.println("1. Addition, 2. Subtraction, 3. Multipilcation, 4. Division, else: stop");
System.out.println("Enter number to corresponding math operation:");
choice = 0;
choice = calc.nextInt();
switch(choice)
{
case 1:
System.out.println("Addition");
System.out.println("Enter first number: ");
add1 = calc.nextDouble();
System.out.println("Enter second number: ");
add2 = calc.nextDouble();
addAnswer = add1 + add2;
System.out.println("Your answer is " + addAnswer);break;
case 2:
System.out.println("Subtraction");
System.out.println("Enter first number: ");
sub1 = calc.nextDouble();
System.out.println("Enter second number: ");
sub2 = calc.nextDouble();
subAnswer = sub1 - sub2;
System.out.println("Your answer is " + subAnswer);break;
case 3:
System.out.println("Multipilcation");
System.out.println("Enter first number: ");
mult1 = calc.nextDouble();
System.out.println("Enter second number: ");
mult2 = calc.nextDouble();
multAnswer = mult1 + mult2;
System.out.println("Your answer is " + multAnswer);break;
case 4:
System.out.println("Divsion");
System.out.println("Enter first number: ");
div1 = calc.nextDouble();
System.out.println("Enter second number: ");
div2 = calc.nextDouble();
divAnswer = div1 + div2;
System.out.println("Your answer is " + divAnswer);break;
default:System.out.println("Good Bye");getOut = true;break;
}
}
}}
I have a method which uses a switch statement to give the user options to select, once they have selected an option and the code in the case has been executed how do I get back into the main method which offers another menu?
Part of my code:
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
....
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
break;
....
}
public static void main(String[] args) {
while (1 == 1) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
....
}
EDIT (full code requested):
/**
* User: Colin Shewell
* Date: 26/11/13
* Time: 10:32
*/
import java.util.Scanner;
import java.util.Arrays; //REMOVE THIS!!!
public class StudentMarks {
static Scanner input = new Scanner(System.in);
static String[] studentNamesArray = new String[10];
static int[][] studentMarksArray = new int[10][3];
static int nameArrayCount, markArrayCount = 0;
static int markOne, markTwo, markThree;
static String studentName;
static void printArrays(){
System.out.println(Arrays.toString(studentNamesArray));
for (int index=0;index<10;index++)
{
System.out.println(studentMarksArray[index][0]);
System.out.println(studentMarksArray[index][1]);
System.out.println(studentMarksArray[index][2]);
}
}
static void addStudent() {
if (nameArrayCount < 10) {
System.out.println("Enter the student's name in the following format - surname, forename: ");
studentName = input.next();
studentNamesArray[nameArrayCount] = studentName;
nameArrayCount = nameArrayCount + 1;
}
else if (nameArrayCount == 10) {
System.out.println("******Array is full, please delete a student before adding another.*****");
}
if (markArrayCount < 10){
System.out.println("Enter the first mark: ");
markOne = input.nextInt();
System.out.println("Enter the second mark: ");
markTwo = input.nextInt();
System.out.println("Enter the third mark: ");
markThree = input.nextInt();
studentMarksArray[markArrayCount][0] = markOne;
studentMarksArray[markArrayCount][1] = markTwo;
studentMarksArray[markArrayCount][2] = markThree;
markArrayCount = markArrayCount + 1;
}
}
static void modifyStudent() {
System.out.println("Wish student would you like to change?");
for(int i=0;i<10;i++){
System.out.println(i + ": " + studentNamesArray[i]);
}
int studentChoice = input.nextInt();
System.out.println("1: Change name.");
System.out.println("2: Change first mark.");
System.out.println("3: Change second mark.");
System.out.println("4: Change third mark.");
System.out.println("5: Change all marks.");
int detailChange = input.nextInt();
switch (detailChange) {
case 1:
System.out.println("Enter the new student name.");
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return;
case 2:
System.out.println("Enter the new mark for mark one.");
int newMarkOne = input.nextInt();
studentMarksArray[studentChoice][0] = newMarkOne;
return;
case 3:
//two
break;
case 4:
//three
break;
case 5:
//all
break;
default:
System.exit(0);
break;
}
}
public static void main(String[] args) {
while (true) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
System.out.println("2: Modify the details of an existing student.");
System.out.println("3: Delete an existing student.");
System.out.println("4: Sort in alphabetical order by name.");
System.out.println("5: Output the student name and corresponding marks in ascending name order.");
System.out.println("6: Output the student name and corresponding marks in descending name order.");
System.out.println("7: Display the student with the highest average mark.");
System.out.println("8: Display the student with the lowest average mark.");
System.out.println("9: Display the average score of all students recorded.");
System.out.println("10: Exit.");
int choice = input.nextInt();
switch (choice) {
case 1:
addStudent();
System.out.println(Arrays.toString(studentNamesArray));
break;
case 2:
modifyStudent();
break;
case 3:
printArrays();
break;
/* case 4:
sortAlphabetical();
break;
case 5:
outputNameMarksAsc();
break;
case 6:
outputNameMarksDsc();
break;
case 7:
highestStudentAvgMark();
break;
case 8:
lowestStudentAvgMark();
break;
case 9:
displayAvgScore();
break; */
case 10:
System.exit(0);
break;
default:
System.exit(0);
break;
}
}
}
}
Just return to the main method. return just exits the method and continues executing code from the line it was called.
case 1:
String newName = input.next();
studentNamesArray[studentChoice] = newName;
return; //exits this method
//break; <-- not needed after a return!
Your code will run in an infinite loop, you can make it run with a conditional flag like this
boolean isRunning = true;
while (isRunning) {
System.out.println("Please select an option:");
System.out.println("1: Add a student.");
....
int choice = input.nextInt();
switch (choice) {
case 1:
isRunning = false;
//your code for case 1
....
}
//rest of the code in main executes now
This will exit the while loop back to the main method