So I wanted my switch to be if the user chooses the switch(b) No it will go back to switch(a) the previous switch. How can I do it? I'm quite new to Java.
switch(a){
case 1:
System.out.println("Here are the available rooms.");
System.out.println("[1] Room No. 1");
System.out.println("[2] Room No. 2");
System.out.println("[3] Room No. 3");
System.out.println("[4] Room No. 4");
System.out.println("[5] Room No. 5\n");
System.out.print("\nWhich room would you like? [1-5]:");
b= sc.nextInt();
switch(b){
case 1:
System.out.println("Room No. 1 costs $200 per stay.");
System.out.println("[1] Yes");
System.out.println("[2] No");
System.out.print("Do you wish to proceed? :");
c=sc.nextInt();
break;
}
break;
}
You would need to use a labelled loop:
theLabel: while (true) { // whatever condition, whatever kind of loop:
switch (a) {
case 1:
// ...
switch (b) {
case 1:
// ...
continue theLabel;
}
}
}
This will jump back to the start of the outer loop, thus it would execute the switch on a again.
But really, this is not a good way to structure it. There is nearly always a better way than using labelled loops, for example extracting some of the nested logic to a method.
In this case, I'd question the use of a switch for "room 1-room 5". Unless there is specific logic for each of the rooms, just use (for example) an array or list or map to store the prices for each of the rooms.
If your question is about going from moving switch b to switch a. Then you can use the recursion for this purpose.
I don't know about return types. So the prototype is
Write the switch(a) in a method. Let's name this method as method1.
write switch(b) in a method. Let's name this method as method2.
method1(Object a)
{
switch(a):
case 1:
//Your code here
if(condition1)
{
method2(a);
}
}
method2(Object b )
{
switch(b):
if(condition2)
{
method1(b)
}
}
Related
How can i check if case (for example 3 ) was choosen to make continuation of story?
I wrote this in java and I would go full detail with story but i dont know how could i .I thought I could nest cases inside each other but if I can choose options(scanner.nextInt();) also add in them.I thought if statement would work better but i dont know how can i check it .I must add that didnt found any answers to this problem before posting.Thanks for reviewing and have a good day
int choice_1 = scanner.nextInt();
switch(choice_1)
{
case 1:
System.out.println("Guard: Its a honor to meet u sir.Its a pleasure to let You through \nBut do u have coin pass?");
if(pass==1){
ending();
}
else{"You should get coin pass first. I am sure that wont be a problem for Prince *laughs*"}
break;
case 2:
System.out.println("*Guard immediately avoided attack and attack u harder that u excepted");
playerHp = playerHp -30;
playerArmorHp = playerArmorHp - 50;
break;
case 3:
System.out.println("Guard : Goodbye Sir");
plan();
break;
default:
System.out.println("Guard is impatient of your not telling anything.Choose option before making him mad.\n"+line);
break;
}
if(switch ( case:3)){
System.out.println("Do u have coin pass?");
int pass = scanner.nextInt();
}
You could change your if clause to if(choice_1 == 3) to get what you want.
I am trying to write a weather condition model. I am having issues with the switch/case. I want one of my cases not available unit two variable are filled by the user. How would I do this? Here is the code clip
switch (choice) {
case 0:
System.out.println("Exit");
break;
case 1:
int yInch = in.nextInt();
yester = CondYest(yInch);
break;
case 2:
System.out.println("Enter/Update Today's Weather Prediction");
int tInch = in.nextInt();
today = CondToday(tInch);
break;
case 3:
System.out.println();
System.out.println("Display Snow Prediction");
System.out.println("Today's Snow Fall is " + today + " inches!");
System.out.println("Yesterday's Snow Fall was " + yester + " inches!");
System.out.println();
break;
default:
System.out.println("Please Try again");
break;
}
} while (choice != 0);
The "beginner level" answer is: have multiple switch statements.
In other words: a "controller" component understands which different "menus" exist, and which pre-conditions need to be met to make that decision.
To turn it into a real world solution, you probably would want to use polymorphism here. Like: having a base class that provides say a showMenu() method which displays choices and asks for the required input. That class also has (abstract) methods for having different behavior.
And then you add multiple child classes that #Override these base methods as needed.
Finally, your controller then "only" has to determine which class to instantiate in order to show the currently valid selections.
I'm new to programming so I'm not able to complete this programme.
I'm required to create a fast food eatery that asks the customer's name, their choice, quantity, phone number, and whether they would like to order something else.
I'm managed to take the inputs from the customer but the only problem is that I can't I can't figure out to add the subtotal if the customers chooses to order something else. Like if they had the total of $10 and make an order of another $10, how am I supposed to add the total and display the bill?
I apologize if I'm not able to explain myself.
Here's what I've done till now:
import java.util.*;
public class KFC
{
public void display_menu()
{
System.out.println("**********WELCOME TO XYZ**********");
System.out.println("MAY I KNOW WHAT WOULD YOU LIKE?");
System.out.println("1.OMG Burger:-");
System.out.println("2.OMG Roller:-");
System.out.println("3.Chicken Snacker:-");
System.out.println("Please enter your choice");
}
public void question()
{
System.out.println("Would you like to have something else?");
System.out.println("To place another order enter 9.");
System.out.println("To check out enter 0.");
Scanner q = new Scanner(System.in);
switch (q.nextInt())
{
case 0:
break;
case 9:System.out.println ("Please proceed.");
new KFC();
break;
default:System.out.println ( " option" );
break;
}
}
public KFC()
{
Scanner sc = new Scanner(System.in);
display_menu();
switch (sc.nextInt())
{
case 1:int a,b,Rate;String s;
double e,t,f,g;
float m;
System.out.println("OMG Burger");
System.out.println("Enter The Quantity");
b=sc.nextInt();
System.out.println("Enter Your Name");
s=sc.next();
System.out.println("Enter Your Mobile Number");
m=sc.nextFloat();
Rate=49;
t=(5.0/100.0)*Rate;
e=b*Rate;
f=t*b;
g=e+f;
question();
System.out.println("***********KFC**********");
System.out.println("Name:"+s);
System.out.println("Mobile Number:"+m);
System.out.println("Choice:OMG Burger");
System.out.println("Quantity:"+b);
System.out.println("Rate:$"+Rate);
System.out.println("Tax:"+f);
System.out.println("Total price:$"+g);
System.out.println("PLEASE VISIT AGAIN. HAVE A NICE DAY!!!");
break;
case 2: System.out.println("OMG Roller");
System.out.println("Enter The Quantity");
b=sc.nextInt();
System.out.println("Enter Your Name");
s=sc.next();
System.out.println("Enter Your Mobile Number");
m=sc.nextFloat();
Rate=59;
t=(5.0/100.0)*Rate;
e=b*Rate;
f=t*b;
g=e+f;
question();
System.out.println("***********KFC**********");
System.out.println("Name:"+s);
System.out.println("Mobile Number:"+m);
System.out.println("Choice:OMG Roller");
System.out.println("Quantity:"+b);
System.out.println("Rate:$"+Rate);
System.out.println("Tax:"+f);
System.out.println("Total price:$"+g);
System.out.println("PLEASE VISIT AGAIN. HAVE A NICE DAY!!!");
break;
case 3: System.out.println("Chicken Snacker");
System.out.println("Enter The Quantity");
b=sc.nextInt();
System.out.println("Enter Your Name");
s=sc.next();
System.out.println("Enter Your Mobile Number");
m=sc.nextFloat();
Rate=40;
t=(5.0/100.0)*Rate;
e=b*Rate;
f=t*b;
g=e+f;
question();
System.out.println("***********KFC**********");
System.out.println("Name:"+s);
System.out.println("Mobile Number:"+m);
System.out.println("Choice:Chicken Snacker");
System.out.println("Quantity:"+b);
System.out.println("Rate:$"+Rate);
System.out.println("Tax:"+f);
System.out.println("Total price:$"+g);
System.out.println("PLEASE VISIT AGAIN. HAVE A NICE DAY!!!");
break;
default:
System.out.println ( "Unrecognized option" );
break;
}
}
public static void main (String[]args)
{
new KFC();
}
}
Initially you are creating new instance of KFC for the a new customer....now when same customer place another order again you create new instance of KFC rather using same instance..bcoz you have placed your logic inside constructor which is totally wrong. As pointed out by oguzhand this will not help in totalling
Constructors are used to initialize the instances of your classes. Often it is used to create new objects often with parameters specifying the initial state or other important information about the object
From the official Java tutorial:
A class contains constructors that are invoked to create objects from
the class blueprint.
For more info on constructors refer
1)So instead of writing your logic inside constructor....write it in a method and call that method.
2)Also as pointed out by RC and oguzhand you should give meaningful names to variable and should use few global variable. For Example
String customerName;
long customerContactNo;
long totalPrice;
int burgerQuantity;
int rollerQuantity;
Points already made by others:
1) Name your variables using some meaningful name
2) Don't do your work in the constructor
It seems as though you're trying to write a program to solve your problem rather than to write a set of classes. When working in Java, you ought to be creating an object oriented solution to the problem.
Ask yourself first about how many of something you have. For each order, how many customers? How many menu items in an order? Since a single customer can order more than one menu item, you should have a class for menu items ordered in a single order.
So far I'm seeing at least three different classes to be written:
1) A class to represent a working day at your restaurant;
2) A class to represent an order; and
3) A class to represent an item in the order.
To get the subtotal for the order, you can just iterate over the OrderItem objects, ask each one how much it costs, and add that to a variable. Store the value in a field on the Order class (or recalculate and return it whenever it's needed) and you're good to go.
I have hit another obstacle in my attempt to create a shape calculator and this time it's using a Loop with my Switch/Case statements allowing the user to select the shapes they wish to calculate.
I am trying to make my Calculator like this. User selects 1 for Triangle, they calculate that and say they now wish to select 5 to calculate a Circle right after, then do another circle calculation again and for however many times they wish and then be able to move onto another shape. Say 6 for a sphere.
So far I've tried using a While (True) loop but it seems once I have made a selection I get stuck in that case and can't go on to select another shape to calculate or select the case that closes/exits the program.
I've reduced my program to an example below cutting out the code needed to make a shapes as the shapes themselves are not the program here. It's trying to make my users range of choice flexible I guess you could say.
Scanner scan = new Scanner(System.in); //take user input
int decision = scan.nextInt();
loop: while (true) {
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
In your loop you need to prompt for and read the next selection. The code you show reads one selection to set decision, but never changes it after that.
Move the scan.nextInt() inside the loop
loop: while (true) {
int decision = scan.nextInt();
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
Problem:
You are taking decision input only once, since it is written outside the infinite while loop. Therefore during execution of infinite loop, decision will never change and every time same case will get executed, giving an impression that program is stuck within a case, which is not the case any ways.
Solution: Move the input statement withing infinite while loop.
while (true) {
int decision = scan.nextInt();
//rest of the code
....
....
}
You must read the decision input everytime (infinite loop)
This should work:
Scanner scan = new Scanner(System.in); //take user input
loop: while (true) {
int decision = scan.nextInt();
switch (decision) {
case 1:
//example
break;
case 2:
//example and so on
break;
case 3:
break;
case 9:
// Quit
System.out.println("You decided to Quit");
break loop;
default:
// Wrong decision
System.out.println("Select a number between 1 and 8 to make a decision or 9 to Quit");
}
//exit program code here
}
I'm writing a program for a slot machine simulator and most of my code is in a while loop.
System.out.println(" * Choose an option: * ");
System.out.println(" * 1: Display credit count. * ");
System.out.println(" * 2: Play Again. * ");
System.out.println(" * 3: End Game. ");
If the user selects 3 to end the game, he is directed to the end game menu.
There is a seprate group of if statements outside of my while loop to determine if the user has left the loop because he is out of credits or he has selected to end game.
//The case in which the user ended the game.
else {
System.out.println("");
System.out.println("You have ended the game. You have finished with a total of: "+credits+" credits!");
System.out.println("");
System.out.println("Next player?");
System.out.println("");
System.out.println("1: Yes, there is another player that would like to start with my "+credits+" credits.");
System.out.println("2: Yes, there is another player, but he will start with 10 credits.");
System.out.println("3: No, End the game.");
selection2 = in.nextInt();
}
What I'm trying to do is: if the user inputs 1, it takes him back to the beginning of the main game loop.
I understand there isn't a goto cmd, so does anyone have an idea of how I could do this? I'm stuck outside a loop and can't get back in! (I've thought about making another loop outside of everything...)
What you could do is create a method called goToLoop()
Inside of that method you place all the code of the loop, so when you want to go back to the loop you simply call goToLoop()
I hope that helps
Here is some incomplete code to give an idea of the state pattern.
interface IState {
void action();
}
class InitialState implements {
void action()
{
System.out.println("");
System.out.println("You have ended the game. You have finished with a total of: "+credits+" credits!");
System.out.println("");
System.out.println("Next player?");
System.out.println("");
System.out.println("1: Yes, there is another player that would like to start with my "+credits+" credits.");
System.out.println("2: Yes, there is another player, but he will start with 10 credits.");
System.out.println("3: No, End the game.");
selection2=in.nextInt();
switch (selection2)
{
case 2:
currentState = new OtherGameState();
break;
}
}
}
Don't exit the loop in the first place...
enum Menu {START, MAIN, EXIT, ETC}
Menu menu = Menu.START;
boolean running = true;
while ( running )
{
switch ( menu )
{
case START:
// show and handle start menu here
// As an extra note, you could/should create methods for each menu (start, main, ...)
// Then call these methods from within the case statements
break;
case MAIN:
// show and handle main menu here
menu = Menu.EXIT; // This is an example of how to "change" menus
break;
case EXIT:
// show and handle exit menu here
running = false; // will cause the execution to leave the loop
break;
case ETC:
// ... etc ...
break;
}
}