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
}
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
}
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.
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;
}
}
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 trying to make a paint dispenser simulation prototype console application with java. searched everywhere and can't seem to find out why this code won't work. I use netbeans. what I'm trying to do with this code is to display the menu, ask user for input, when user inputs a number it selects that option from menu and then I need to start getting those options to work once I have the menu working. Any help is appreciated thanks. My code so far is shown below.
package paintdispensersimulation;
import java.util.Scanner;
/**
*
* #author Kris Newton (M2124910)
*/
public class PaintDispenserSimulation //
{ //Open Public Class
public static void main(String[] args) //
{ //Start Main
Scanner in = new Scanner (System.in); //
int option; //
boolean quit = false; //Declare variables
do //
{ //Start Do
System.out.println("Please Make a selection:"); //
System.out.println("[1] Process New Job(Decimal Values)"); //
System.out.println("[2] Process New Job(RGB Hexadecimal Values)"); //
System.out.println("[3] Calibrate Dispenser"); //
System.out.println("[4] Display Summary Of Jobs"); //
System.out.println("[0] Exit"); //Print Menu
option = in.nextInt(); //Declare User Input
switch (option) //Declare Switch
{ //Start Switch
case 1: //If Option = 1
System.out.println("You Chose To: Process New Job(Decimal Values)"); //Print
break; //Break
case 2: //If Option = 2
System.out.println("You Chose To: Process New Job(RGB Hexadecimal Values)"); //Print
break; //Break
case 3: //If Option = 3
System.out.println("You Chose To: Calibrate Dispenser"); //Print
break; //Break
case 4: //If Option = 4
System.out.println("You Chose To: Display Summary Of Jobs"); //Print
break; //Break
case 0: //If Option = 0
quit = true; //Quit
break; //Break
default: //If Option Invalid
System.out.println("Selection Invalid: Please enter a valid selection."); //Print
} //End Switch
} //End Do
while (!quit); //While Quit = True
System.out.println("You Chose To: Exit"); //Print
} //End Main
} //End Public Class
This is the message I get when trying to run.
run:
java.lang.VerifyError: Constructor must call super() or this() before return in method paintdispensersimulation.PaintDispenserSimulation.<init>()V at offset 0
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2442)
at java.lang.Class.getMethod0(Class.java:2685)
at java.lang.Class.getMethod(Class.java:1620)
at sun.launcher.LauncherHelper.getMainMethod(LauncherHelper.java:494)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:486)
Exception in thread "main" Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I am able to run this code in eclipse.
VerifyError can mean the bytecode is invalid.
Basically, this is a compiler bug, or if class file is corrupted
Try compiling with a different JDK version and on a different machine.