Infinite Java loop - java

Please look at this code and tell me where I am making a mistake? I am new to java and I am getting an infinite loop on the below switch statement.
Below is the full method I am calling with system.out as placeholders until I fix the infinite loop.
Thanks in advance
public void startuserinterface()
{
Scanner Menukeyboard = new Scanner(System.in);
displaymainmenu();
mainMenuChoice = Menukeyboard.nextInt();
while(mainMenuChoice!=EXIT)
{
switch(mainMenuChoice){
case DISPLAY_ROOMS : {
System.out.println(" I am displaying rooms ");
break;
}
case DISPLAY_GUESTS : {
System.out.println(" I am displaying guests ");
break;
}
case PROCESS_RESERVATION :
{
System.out.println(" I am displaying reserving ");
displayreservationmenu();
resMenuChoice = Menukeyboard.nextInt();
runResMenu(resMenuChoice);
break;
}
case PROCESS_PAYMENT :
{
System.out.println(" I am payin ");
break;
}
}
}
System.out.println(" Goodbye ");
displaymainmenu();
}

After switch statement is done and break occurs, the condition goes back to while loop. And it again checks the same value i.e does not equal to Exit and hence it again runs the switch statement.
Basically you are checking again and again on same Exit without changing the value. And since on first attempt the value was not equals to Exit which makes it true every time while is checked, so it will run forever.

You have to end while loop. In given example break; only ends switch statement and while loop is executed again. And because there was no place to change the while loop condition, it means that this loop will be always true -> will be executed forever.

Related

System.out.println(); is printing two lines

I've recently started studying Java and I already had my first problem. Currently I'm making a text adventure game (written in Java) and I can't continue because the program is printing out two lines but that I don't want it to. I don't how I can make it print out only one line.
In the last bit of the program there is a system.out.print("hello")
import java.util.Scanner;
public class TextAd2 {
Scanner sc = new Scanner(System.in);
//Name
String Pname;
public static void main(String[] args) {
//connection
TextAd2 con;
con = new TextAd2();
con.info();
con.start1();
}
public void info() {
System.out.println("Hello!");
System.out.println("Your Name? ");
Pname = sc.nextLine();
System.out.println("Hello " + Pname);
System.out.println("Wana Start The Game or Stop?");
String text1 = sc.nextLine();
switch (text1) {
case "Start":
start1();
break;
case "Stop":
System.exit(0);
break;
default:
System.out.println("Unknown Command.");
}
}
public void start1()
{
//it starts to print this twice
System.out.println("hello");
}
}
I actually don't think that the system.out.print is the problem, maybe the program is just reading the 'start1()' twice that's why it's printing "hello" two times. I did this in an if else statement and it's doing the same thing too. I don't know the code to how to prevent this either way. I am doing something wrong but I don't know what is the probelm
You can calling twice con.start1();
Once in your main():
con.info();
con.start1();
And the second time in your switch:
case "Start":
start1();
break;
At first, the execution reaches this line:
con.info();
So info starts running. Then execution reached:
case "Start":
start1();
break;
So start1 starts executing and prints Hello.
However, remember that the deepest call stack is still on the info method. After printing Hello, start1 returns it is popped from the call stack. break; then runs and info also pops from the call stack. Now, we will go to the next line after info(), which is start1!
That's why it is printing twice. To stop this, simply remove start1 from the main method,

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 do I keep looping in a do-while loop as long as the default part of a switch triggers?

What I am trying to accomplish: when the user types in anything other than 1 or 2, there will be a prompt saying "I don't understand you" and it would ask the user to choose 1 or 2 again without having to run the program each time.
Something like this:
do {
String a = input.nextLine();
num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
break;
case 2:
System.out.println("goodbye");
break;
default:
System.out.println("I don't understand you");
}
} while (num == default);
I know typing this will give me an error, so how do I compare it?
First, you have a potential infinite loop because the value for num which controls the stoping condition is never updated inside the loop.
Second, you could introduce a local variable to track when the user input was understood and exit the loop on that condition:
boolean understood;
do {
understood = false;
String a = input.nextLine();
int num = Integer.parseInt(a);
switch (num) {
case 1:
System.out.println("hello");
understood = true;
break;
case 2:
System.out.println("goodbye");
understood = true;
break;
default:
System.out.println("i dont understand u");
break;
}
} while (!understood);
What you asked is technically a while(true) since everything which is not 1 or 2 is default. Also you should probably put your scanning bit in the loop.
If you try to check if value is different from 1 and 2 to ask again for a valid option:
do
{
// stuff
}
while( num != 1 && num != 2)
Since "default" is a keyword you just can not compare it to anything. It's meaningless though, because in your condition you used all possible cases(case 1 and case 2), so your code will never end, printing either "hello" or "goodbye" forever.

How to terminate while loop once response is correct?

I'm working on this program that says "get some ice cream"/"put on a jacket" if you type "hot/cold". However, even after you type in hot/cold, the program keeps going in the while loop. How can I make this program keep asking the user for their condition until they correctly respond with one of the two answers, and prevent it from continuously asking for a response even after the user types a correct answer?
import java.util.Scanner;
public class IfStatement {
public static void main(String[] args) {
boolean run = true;
while(run) {
System.out.println("What is your condition: ");
Scanner input = new Scanner(System.in);
String x = input.nextLine();
if(x.equals("hot"))
System.out.println("Get some ice cream");
else if(x.equals("cold"))
System.out.println("Put on a jacket");
else
System.out.print("Try again, what is your condition: ");
}
}
}
your loop iterates as long as run is true. what you need to do is therefore to set run to be false once the input is correct. like this
if(x.equals("hot")){
System.out.println("Get some ice cream");
run = false; // setting run to false to break the loop
}
else if(x.equals("cold")) {
System.out.println("Put on a jacket");
run = false; // setting run to false to break the loop
}
break statement can be used as well.
You may also use do while loop.
In this case, you would have the ability to check your condition against "x" when the loop ends, and hence would not need additional flag.
However, do while loop will run at least once, which I assume you need as per your requirement.

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