Calling previous switch in Java - java

I'm making a simple command line system where the user is supposed to be able to choose what they want to do. Therefore I've made a switch that takes a number as input and outputs whatever I choose, although I have now clue on how to return the user to the place where they can input again.
Let's say two of the cases looks like this:
case 6:
System.out.println("----- List of available Systems: ----- ");
break;
default:
System.out.println("You pressed a non-existing number. Please try again.");
break;
}
Now if the user (me) types any number above 6 it goes to the default and stops there. Is there anyway to make it jump back to the first "Menu" that asks for input?
Thank you in advance.

You can wrap it in a loop, e.g. a while:
while (var < 1 || var > 6) {
switch(var) {
...
}
}
However, this way, you need to make sure, that you won't be stuck in an infinite loop. This can be solved, e.g. by using a label:
end: while (var < 1 || var > 6) {
switch (var) {
case 1:
// do something
break end;
...
default:
System.out.println("Please try again.");
break;
}
}
This way, the break statements will break out of the while loop. Java labels are basically a very limited version of goto.

How about something more verbal..
int myno;
Scanner scanner =new Scanner(System.in);
boolean exit = false;
while(!exit){
System.out.println("1. Menu 1");//Modify your menu
System.out.println("2. Menu 2");
System.out.println("3. Menu 3");
System.out.println("4. Menu 4");
System.out.println("5. Menu 5");
System.out.println("6. Menu 6");
myno = scanner.nextInt();
switch(myno){
case 1 :
//do something
break;
case 2 :
//do something
break;
case 3 :
//do something
break; //add for remaining cases
case 7 :
exit = true;//for exit
break;
default :
// do something //set exit = true if you what to end the program for other inputs
}
}
try this

Related

how do i keep taking choices in switch case until exit choice is entered in java [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 4 years ago.
I want to keep taking choices from the user until he gives an exit statement.
How can I come out of the while loop if I use it in this code?
Is there any other way to take choice from the user than switch case:
And if I try to use while loop for this then it is going in an infinite loop:
Code:
import java.util.Scanner;
class lib
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String c;
int j=5,a=5,s=5,cg=5;
int d=0;
System.out.println("Available Copies :");
System.out.println("java=5,ada=5,sp=5,cg=5");
System.out.println("enter book title");
//System.out.println("enter exit for exit if don't want to search");
c=in.nextLine();
while(d==0)
{
switch(c)
{
case "java":
System.out.println("author is herbert");
System.out.println("price :500");
j--;
break;
case "ada":
System.out.println("author is corman");
System.out.println("price :600");
a--;
break;
case "sp":
System.out.println("author is dhamdhire");
System.out.println("price :550");
s--;
break;
case "cg":
System.out.println("author is pearson");
System.out.println("price :700");
cg--;
break;
case "exit":
d++;
break;
default:
System.out.println("book not available");
}
}
if(j!=0)
System.out.println("number of available copies is"+j);
}
If you want to keep taking input from the user until they give the exit command then you need to keep taking input inside the while loop. Move c=in.nextLine() into the while loop right before the switch statement.
If you want to prompt the user as well then add a print statement at the end of the loop right after the switch statement ends, and instead move c=in.nextLine() to the end of the while loop right after the print statement. Something like:
System.out.print("Enter the title of another book: ");
c=in.nextLine();
I think what your looking for is moving your nextLine inside the while loop.
This part of the code:
//System.out.println("enter exit for exit if don't want to search");
c=in.nextLine();
while(d==0)
{
.....
To this:
//System.out.println("enter exit for exit if don't want to search");
while(d==0)
{
c=in.nextLine();
.....

How do i use try-catch statement with switch case but loop the swich case?

I am very new to Java and im trying to use try-catch statements. I would like to add a try catch case, but when i add it, the message just prints once and ends. I woudl like to reprint:
System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
System.out.println("Typing other numbers will end the Chatbot");
but the program just ends. Is there a way to loop the try-catch statement?
Scanner userinput = new Scanner(System.in);
int startup;
//popup for 1 to chat, 2 to play and 3 to edit
while (true) {
try {
System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
System.out.println("Typing other numbers will end the Chatbot");
startup = userinput.nextInt();
switch (startup) {
case 1:
ConversationBot chat = new ConversationBot();
chat.ChattingBot();
break;
case 2:
GameBot game = new GameBot();
game.GamingBot();
break;
case 3:
EditBot edit = new EditBot();
edit.EditingBot();
break;
default:
System.exit(0);
}
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
break;
}
String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);
}
Thank you for the help.
BTW this is the returnChoiceOf Chatbot method
public static String returnChoiceOfChatbot(int input) {
String returnChoice = null;
switch (input) {
case 1:
returnChoice = ("You have chosen to chat with me!");
break;
case 2:
returnChoice = ("you have chsen to play word games with me!");
break;
case 3:
returnChoice = ("Please enter an input that you would give to the Chatbot.");
break;
default:
System.exit(0);
}
return returnChoice;
}//end of returnChoice method
You need to replace the line break; with continue; in your catch block. You want to ask the user for a new input if it wasn't a number. Otherwise that break breaks the whole while loop and prevents it from running again. This said, it should read:
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
continue; // Jump back to the beginning of the while-loop
}
Also check if you need to move these two lines:
String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);
outside of your while loop. While it's not clear to me what they are for, it looks like you might want to run them only once after the while loop was left.
The break statement (when used without a label to specify what to break out of) will exit the nearest switch, while, for or do .. while loop.
You generally have to use it with switch as you do to stop the execution falling through to the next case - e.g. if you didn't have the breaks and the user selected 1, it would execute the code for all three cases, and then exit the program.
Inside your catch block however, the break exits the while loop. Since the intention is to tell the user their input is invalid and then ask for new input, this isn't what you want to do here. You could change the break to a continue which would abort the current iteration of the while loop and start the loop again, however generally speaking this sort of flow control will make your program harder to follow and therefore maintain.
I'm guessing you put the last break in to skip over the returnChoiceOfChatbot(...) code when the input is invalid. But this is exactly what exceptions are for - aborting the normal flow of code when something unexpected happens. So just move the "normal flow" code all inside the try block, and you won't need break (or continue) at all:
while (true) {
try {
System.out.println("Press \"1\" to chat" + " & " + "\"2\" to play games" + " & \"3\" to edit the conversations");
System.out.println("Typing other numbers will end the Chatbot");
startup = userinput.nextInt();
switch (startup) {
// cases in here as before, omitted for brevity
}
String returningCode = returnChoiceOfChatbot(startup);
System.out.println(returningCode);
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid User Input. Please enter a value from 0 to 4.");
break;
}
Just remove the break. It doesn't have anything to do with the catch specifically, just with the break that you wrote in it.

How to go back to upper position in a program

I am trying to make node based big integer calculator in Java, and I want to re print the menu of calculator after operations. I thought of using goto but it gives error saying goto byte expected.
I am new in java, so can any one help me with the below demo code-
up:
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result = 0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
default:
goto up;
}
Thank you, I just want to reprint the menu.
You should use a simple while-loop for that. Maybe create a boolean as the running condition and set it to false, when the user types something else than 1 or 2.
Java does not support goto, as it is a reserved keyword.
Also, IMHO, using goto is not a great way to write a program.
A better approach would be to write a function which displays the menu and call that function whenever you want. Or just use a do-while loop.
Here is a way to look at "goto" in a java environment, using your code as the example:
public void addUp() {
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
int i=s.nextInt();
System.out.println("ENTER FIRST NUMBER ");
int a=s.nextInt();
System.out.println("ENTER SECOND NUMBER ");
int b=s.nextInt();
int result = 0;
switch(i)
{
case 1:
result=a+b;
break;
case 2:
result=a-b;
break;
default: addUp();
}
}
Java doesn't use goto as it doesn't really fit into the Object-Oriented concept (I faced the same problem years ago when I made the switch from Basic). So you'll have to reconsider your code's logic to implement a loop of some sort.
Something like:
do {
// add an exit option to the menu
System.out.println("YOU HAVE FOLLOWING CHOICES : ");
System.out.println("1. ADDITION");
System.out.println("2. SUBTRACTION ");
System.out.println("3. EXIT");
// continue with the same logic you had before
} while (i !=3)
I hope that helps.
note: if you lookup the keyword goto in Java documentation, you'll see that it's reserved but it doesn't do anything. They probably reserved it as a placeholder for these situations

Trouble returning to command options using loops/ only one command is being run (JAVA)

This is my first time on this site. I am taking a course in Java right now and I am having some trouble with this code/program that I am supposed to make that allows the user to select whether they want to see "good monkeys", "bad monkeys" or "show monkeys". It is nowhere near done but I am having trouble returning to the command screen/area after a command is completed. I would like the commands to be used as many times as possible. Secondly, my program treats every input if someone put in "Good Monkey". So if you put in a word like "pineapple", it will still greet you with the output designated for the "Good Monkeys" input.
I've looked online and seen that maybe I should use a "do-while" loop and use "switch". Any input/ help would be greatly appreciated. Thank you so much!
Here is my code: public class and public static and Scanner import are in this code, but for some reason I cannot add them into this post without messing up the formatting of the code.
Scanner jScanner = new Scanner(System.in);
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
String userChoice = jScanner.nextLine();
for (int b= 1; b < 11000; b++)
{
if (userChoice.equalsIgnoreCase("Good Monkeys"));
{
System.out.println("You have selected Good Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner goodMonkeyScanner = new Scanner (System.in);
int userChoiceGood = goodMonkeyScanner.nextInt();
if (userChoiceGood >= 3 && userChoiceGood <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else if (userChoice.equalsIgnoreCase("Bad Monkeys"))
{
System.out.println("You have selected Bad Monkeys");
System.out.println("How many monkeys do you want? Put in a integer between 3 and 20");
Scanner badMonkeyScanner = new Scanner (System.in);
int userChoiceBad = badMonkeyScanner.nextInt();
if (userChoiceBad >= 3 && userChoiceBad <= 20)
{
System.out.println("Here you go");
System.out.println("Monkeys (metapohorical)");
break;
}
else
System.out.println("Sorry this doesn't work");
}
else if ((userChoice.equalsIgnoreCase("Show Monkeys")))
{
System.out.println("Monkeys");
System.out.println("0");
System.out.println("\\/");
System.out.println(" |");
System.out.println("/\\");
break;
}
else
{
System.out.println(" Wrong Answer. Try again");
}
break;
}
}
}
}
First, you need to define the loop. Second, you need to put the input instruction inside the loop.
I'll include a done variable to detect when the user wants to escape
So, let's code:
Scanner jScanner = new Scanner(System.in);
boolean done = false;
while(!done) {
System.out.println("please enter Good Monkeys, Bad Monkeys or Show Monkeys");
System.out.println("(or enter 'done' to exit");
String userChoice = jScanner.nextLine();
swithc(userChoice.toLowerCase()) {
case "good monkeys":
/*
* The code for this option
*/
break;
case "bad monkeys":
/*
* The code for this option
*/
break;
case "show monkeys":
/*
* The code for this option
*/
break;
case "done":
done = true;
break;
default:
System.out.println("Your input isn't what I expected!\nTry again!");
break;
}
}
The code, explained:
That while(!done) stuff can be read as "while 'not done' do what follows"
userChoice.toLowerCase(): I convert the userChoice to lower-case, to simplify comparissons. That way, I only need to compare the string with other lower-case strings
switch(userChoice.toLowerCase()): ... hmmm... I think you can figure it out yourself ;)
That default block is what happens if no other case is valid
The "done" block will set the done variable to true, and thus it will terminate the loop
Important: ALWAYS end the case blocks with break
Further reading:
The Java Tutorials: Language basics
The while and do-while statements
The switch statement
Also, I recommend you study Flowcharts and, before start coding, try to draw in paper a flowchart of your program. That way, you will have a clear image of your program before you start writing the very first line of code.

JAVA: Menu Infinite-loop

This is a follow up to a question I have asked previously that did get answers that should have fixed my problem, but unfortunately did not. My program reads in a text file and organises data before giving the user a number of options. When the program gets to this point I want to user to be able to select an option, that performs an operations, but then returns the user back to the start point to be able to perform more operations. This is the answer I liked best (thanks to Octopus) and am currently trying to implement.
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
}
As I see it, the program should enter the loop initially, allow the user to input a selection, then return back to "enter a value". However, the program does not return, and terminates after one operation. How can I prevent this to continue the program running infinitely?
Thanks in advance!
The current while loop is there to get valid input -- don't change it.
You need to wrap this code in another while loop that loops til a sentinal value is entered.
while (!isSentinalValue) {
while (inputNotValid) {
// get valid input
}
}
Edit
More specifically in pseudocode:
while (!isSentinalValue) {
input = invalidValue
while (inputNotValid) {
getInput
}
use input to do menu things
}
So I would not have the switch block inside of the inner loop, since that loop concerns itself only with making sure that the input entered is valid. Do the switch block outside of the inner loop, and be sure to set the sentintal value that allows the user to escape the outerloop when appropriate.
Your while(choiceentry < 1 || choiceentry > 3) condition is wrong. If you want it to loop , then you have to make it between 1 and 3 .
So this also means that you will have to change your choiceentry initialization value. This will work.
int choiceentry = 1
while(choiceentry >=1 && choiceentry <= 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
....
}
your loop only runs while choiceentry is less than 1 or greater than 3. As soon as the user enters one of those values, the loop exits.
Learn to use a debugger.
place the following code after switch
if(choiceentry == 4){
break;
}
Now when you will input 4 then it will be terminated, you can use any value other then 4
Use break only when user wants to quit(Say when choiceentry=0). You can use "continue" to make loop infinite. Sample code is given for reference
int choiceentry = 1; // can set any int value except 0 (exit code is 0 for this example)
Scanner scanchoice = null;
while (choiceentry != 0) {
System.out.println("Enter \"1\", \"2\" or \"3\" ..Press 0 to quit");
scanchoice = new Scanner(System.in);
if (scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
// System.out.println("choiceentry=" + choiceentry);
switch (choiceentry) {
case 0:
{
System.out.println("Bye Bye");
break;
}
case 1:
{
System.out.println("In Case 1");
continue;
}
case 2: {
System.out.println("In Case 2");
continue;
}
case 3: {
System.out.println("In Case 3");
continue;
}
}
}

Categories