i'm working on a project, it has a menu, i used (do,while and switch) main menu has a sub menu.
problem is sub menu dose not return to main menu
my work
case 4 :
do {
int cho = in.nextInt();
switch (cho) {
case 1 : break;
case 2 : break;
case 3 : break;
case 4: break; // i want this to return back to main menu
} // switch main
} while (choice !=4) ;// end sub
break;
When user enters 4 (sub menu) it continues to loop the sub menu instead of returning
Use cho instead choice:
do {
int cho = in.nextInt();
switch (cho) {
case 1 : break;
case 2 : break;
case 3 : break;
case 4: break; // i want this to return back to main menu
} // switch main
} while (cho!=4) // Use cho instead choice
The break statements in your switch only break out of the switch. I'm not quite sure why this switch is even there. choice is never touched inside the do...while so it will never break. I would guess the solution would be to set choice to in.nextInt() instead of cho.
Related
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
}
so here is my case to make a long code short.
Let's say, we have a JOptionPane with 3 buttons.
boolean loopGameInterface = true;
while(loopGameInterface){
int chooseGame = JOptionePane........
switch(chooseGame) {
case 0:
case 1:
case 2:
System.exit(0);
}
}
So the problem is, when I click (example) second button, it goes to case 1. That's fine. But when the code inside case 1 is executed, it goes directly to case 2 and exit my program, instead of just looping the gameInterface?
You need to add break; at the end of each case. This is true for all switch statements by the way, not just when you are using a JOptionPane
switch(chooseGame) {
case 0: /* Your code */
break;
case 1: /* Your code */
break;
case 2:
System.exit(0);
default : "Give some default case too"
}
Its because you haven't added the break statement. If you are not adding break all the cases below the case which matches will be executed. For eg:
switch(ch) {
case 1:
/* some code without break */
case 2:
/* some code without break */
case 3:
System.exit(0);
}
In the above example if ch=1 then all case 2 will also be executed and then case 3.
If ch=2 then only case 2 and case 3 will be executed since case 3 is below case 2. So you need to add break after each case.
I am looking to update my code to loop my swtich statement if a user inputs anything that doesn't have an option defined in it. I have scoured the numerous pages here that return from various search terms and have come close but so far no luck still.
My code here should get any one that wants to take a stab at it going.
java.util.Scanner;
//import java.lang.Character.*;
//Thought this was needed to grab single char but its not
public class caseloop {
//main Method
public static void main(String[] args)
{
Scanner input=new Scanner(System.in); //make so you can give input
boolean go = true; // for starting main outer loop
boolean run=true; // start inner loop
while (go==true)
{
while (run==true)
{
//Output
System.out.println("Enter option \n 1-Do this \n 2-Do this thing \n 3-Do this other thing");
int option= input.nextInt(); //grab option number
switch(option)
{
/*
* This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
*/
case 1:
System.out.println("Option1");
break;
case 2:
System.out.println("Option2");
break;
case 3:
System.out.println("Option3");
break;
/*case 4:
System.out.println("Option1");
System.out.println("Option2");
System.out.println("Option3");
break;
*
*
* Case 4 was for debug
*
*/
default:
System.err.println("Invalid option selected");
/*
* On input that is not defined with in the switch-case it will revert to "default"
* this fault staement needs to tell ther usere their option is not vaild and then
* prompt them to try it again to enter an option. I can not get it to reprompt.
* I have tried a while and an if loop both sorta worked but did not actually loop
* back to display again. I have been instucted that I am to not use a try catch statment
* unless of course that is the only viable option in whichcase I will use it anyways.
*/
//stupid default statement and its redundent built in "break;"
}
run=false;
}
/*
* Outer Loop to prompt user if they want to run the entire program again with new entries.
*/
if (run == false)
{
System.out.println("Would you like to run again? Y/N");
char again = input.next().charAt(0);
again = Character.toUpperCase(again); //force all leters inputed to upper case, lower would work too if i change if conditions
if (again == 'Y')
{
run = true;
}
else if (again == 'N')
{
System.out.println("Goodbye.");
go=false;
}
else
{
System.err.println("Invalid entry. Try again.");
}
}
}
}
//System.err.println("An error occured please try again");
}
Any assistance in this would be much appreciated.
You are using the run variable in a very odd way. Since you set the run to false at the end of the loop, the loop will never repeat. If you change it around so that only the valid options set run=false, inputting the wrong option will cause the loop to run one more time.
Remove run=false at the end of the switch statement, add it after the System.out.println("OptionX");
The "run=false" part is not in the right place, it's executed whatever the answer (valid or not).
You should move the "run=false;" inside each valid case statement,like :
case 1:
System.out.println("Option1");
run=false;
break;
By the way : "while (run==true)" is redundant, you can write "while(run)"
The problem is that after executing statement under default, it sets the boolean run to false, and thus, comes out of the loop. What we need is a way to skip this:-
run = false;
and instead go directly to loop condition. One solution would be to add a 'continue' statement under default:-
switch(option)
{
/*
* This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
*/
case 1:
System.out.println("Option1");
break;
case 2:
System.out.println("Option2");
break;
case 3:
System.out.println("Option3");
break;
/*case 4:
System.out.println("Option1");
System.out.println("Option2");
System.out.println("Option3");
break;
*
*
* Case 4 was for debug
*
*/
default:
System.err.println("Invalid option selected");
continue; //this causes control to go back to loop condition
}
You can Add a label to your loop. This way when you got the right option you'll exit the loop.
loop: switch(option)
{
/*
* This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
*/
case 1:
System.out.println("Option1");
break loop;
case 2:
System.out.println("Option2");
break loop;
case 3:
System.out.println("Option3");
break loop;
/*case 4:
System.out.println("Option1");
System.out.println("Option2");
System.out.println("Option3");
break;
*
*
* Case 4 was for debug
*
*/
default:
System.err.println("Invalid option selected");
continue; //this causes control to go back to loop condition
}
I would like to write some code in java that can in a switch or something calls the same case multiple times, using some code that will be the same for most or all cases in the middle. Right now I have to repeat half of the code for each case because it's surrounded by case sensitive code. The code in my mind would look something like this, variable ranges from 0-3 and break just means stop executing until next call to that case, I understand that it is probably something besides break if it exists,
switch(variable){
case 0:
case 1:
if(other factors)
//add item to next spot in array
case 2:
case 3://all cases
//add items to next 3 spots in array for all cases
break;
case 0:
case 1:
if(other factors)
//add item to next spot in array
case 2:
case 3://all cases
//add more items to next spot in array
break;
case 1:
case 2:
if(other factors2)
//add item to next spot in array
break;
case 3:
//add item to next spot in array
case 0:
case 1:
case 2://all cases
//add items to next spot in array
break;
case 1:
case 2:
if(other factors2)
//add item to next spot in array
break;
case 3:
//add item to next spot in array
}
I'd start with splitting your pseudo switch into real switches:
switch(variable){
case 0:
case 1:
if(other factors)
//add item to next spot in array
case 2:
case 3://all cases
//add items to next 3 spots in array for all cases
}
switch(variable){
case 0:
case 1:
if(other factors)
//add item to next spot in array
case 2:
case 3://all cases
//add more items to next spot in array
}
switch(variable){
case 1:
case 2:
if(other factors2)
//add item to next spot in array
break;
case 3:
//add item to next spot in array
case 0:
}
switch(variable){
case 1:
case 2://all cases
//add items to next spot in array
break;
case 1:
case 2:
if(other factors2)
//add item to next spot in array
}
This should meet your requirements.
I then would extract each switch block in its own method, to make it easier to understand and read.
You might consider extracting all this into a small class hirachy:
class DefaultExecutor{
void do(){
step1();
step2();
step3();
step4();
}
void step1(){//all cases class of the first switch statement}
//... similar methods for the other switcht statements
}
class CaseZeor extends DefaultExecutor{
// override step1-4 as required for special treatment of case 0
}
// ... further classes for cases 1-3
You can do this with multiple switch statements. When you use break; it drops out the switch block in any case.
Switch will not fit for that, you will need to perform the checks with some if-else statements (or some separate switch statements as Peter said).
From JLS:
No two of the case constant expressions associated with a switch statement may have the same value.
So I want to do a certain action 60 % of the time and another action 40% of the time. And sometimes have it doing neither. The best way I can think to do this is through switches and making a bunch of cases. An example is below if this doesn't make any sense to ya'll.
My question is, is there a better way?
Is there a way to just do Case 0-5 does action 1 all in one statement?
Random rand = new Random(50);
switch(rand.nextInt())
{
case 1:
{
do action 1
}
break;
case 2:
{
do action 1
}
break;
case 3:
{
do action 1
}
break;
case 4:
{
do action 1
}
break;
case 5:
{
do action 1
}
break;
case 6:
{
do action 1
}
break;
case 7:
{
do action 2
}
break;
case 8:
{
do action 2
}
break;
case 9:
{
do action 2
}
break;
case 10:
{
do action 2
}
break;
}
Something like this would be much more readable IMO:
if( Math.random() >= probabilityOfDoingNothing ){
if( Math.random() < 0.6 ){
action1;
}else{
action2;
}
}
Re. your question about cases, the following is equivalent to your code:
Random rand = new Random(50);
switch(rand.nextInt())
{
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
{
do action 1
}
break;
case 7:
case 8:
case 9:
case 10:
{
do action 2
}
break;
}
Random rand = new Random(50);
int n = rand.nextInt(11);
if(n<=6)
do action 1
else
do action 2
You need to use nextInt(n) to generate a number between 0 (inclusive) and n (exclusive). In this case we use 11 which gives us a number between 0 and 10. Anything below 6 (60% chance) we do action 1 otherwise do action 2.
See this for more details on the Random class.
Using a switch statement is only useful if you have a lot of actions you want to perform, where the action performed depends on something. For example a different action is performed based on the current month. Its quicker than writing if-else statements.
If you want same action to happen for multiple cases, then don't put break. For example
case 1:
case 2:
do action 1; break;
In this case, action 1 will happen for both case 1 and 2.
All you can do is do not apply break in between like
case 1:
case 2:
case 3:
case 4:
case 5:
do action 1;
break
case 6:
case 7:
do action 2;
break
default : break;
or
use if-else if you have range of value ..
There are many approaches to "random" behavior. Some are easier to implement than others but these sacrifice the entropy bucket. Random() is an expensive operation. Switch is useful for complicated signalling, but for a binary decision if is what you want:
int signal = (int)(System.currentTimeMillis() % 5);
if(signal==0 || signal == 1){
doActionTwo();//one third of the time
}else{
doActionOne();//two thirds of the time
}