This question already has answers here:
Switch statement just returning the last case
(4 answers)
Closed 8 years ago.
I am trying to switch states. I first start off in the START_STATE. I then prompt the user to whether go to the FAIL_STATE or GO_STATE. However it seems that whether they type in "go" (For the GO_STATE) for fail (for the FAIL_STATE), neither of the other cases are activated. What is a solution for this issue?
import java.util.*;
public class dfa {
static State state;
public enum State
{
START_STATE,
GO_STATE,
FAIL_STATE,
};
dfa(State state)
{ state = this.state;}
/**
* #param args
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String line;
state = State.START_STATE;
switch(state)
{
case START_STATE:
System.out.print("In start state \n ");
System.out.println("Which state you want to go to? \n");
line = input.next();
if(line.equals("go"))
{
state = State.GO_STATE;
System.out.print(" Go hello");
}
else if(line.equals("fail"))
{
state = State.FAIL_STATE;
System.out.println(" Fail hello ");
}
break;
case FAIL_STATE:
System.out.println("fail state");
break;
case GO_STATE:
System.out.println("go state");
break;
default:
System.out.println("Default");
break;
}
System.out.println("made it here");
}
}
Output:
(When "go" is typed)
Go hello
made it here
(When "fail" is typed)
Fail hello
made it here
Your case START_STATE don't have a break. Then it will always go to next case witch is case FAIL_STATE: witch has a break.
Your switch-case should follow this order.
switch(condition){
case con1:
// do something
break;
case con2:
// do something
break;
default:
// do something
break;
}
You simply forgot a break in the case for the START_STATE:
case START_STATE:
System.out.print("In start state \n ");
System.out.println("Which state you want to go to? \n");
line = input.next();
if(line.equals("go")) {
state = State.GO_STATE;
System.out.print(" Go hello");
} else if(line.equals("fail")) {
state = State.FAIL_STATE;
System.out.println(" Fail hello ");
}
break; // <-- here
You are missing break statement at the end of the case START_STATE, so it just falls through to the next case:
case START_STATE:
System.out.print("In start state \n ");
System.out.println("Which state you want to go to? \n");
line = input.next();
if(line.equals("go"))
{
state = State.GO_STATE;
System.out.print(" Go hello");
}
else if(line.equals("fail"))
{
state = State.FAIL_STATE;
System.out.println(" Fail hello ");
}
break; // Missing from OP
Related
I am trying to create an issue tracking System, but I am having a bit of a problem, every time I run the code, it does not come back to the menu, it just loops. I want my code to come back to the menu whenever i describe my issue.
package com.company.TrackingSystem;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
private void menu() {
boolean is = true;
System.out.println("---Menu---");
System.out.println(
"1.Create new Issue\n" +
"2.Mark Issue as solved\n" +
"3.View unsolved Issues\n" +
"4.View solved Issues\n" +
"5.Exit\n"
);
}
}
My tracking class
package com.company.TrackingSystem;
public class TrackingSystem {
private String createIssue;
private boolean issueSolved;
public TrackingSystem(String createIssue, boolean issueSolved) {
this.createIssue = createIssue;
this.issueSolved = issueSolved;
}
public String getCreateIssue() {
return createIssue;
}
public void setCreateIssue(String createIssue) {
this.createIssue = createIssue;
}
public boolean isIssueSolved() {
return issueSolved;
}
public void setIssueSolved(boolean issueSolved) {
this.issueSolved = issueSolved;
}
}
Example output:
---Menu---
1.Create new Issue
2.Mark Issue as solved
3.View unsolved Issues
4.View solved Issues
5.Exit
Select option >> 1
*** Create an Issue***
Describe your Issue:
*** Create an Issue***
Describe your Issue:
as
*** Create an Issue***
Describe your Issue:
sa
*** Create an Issue***
Describe your Issue:
as
Let's look at this function:
private ArrayList<TrackingSystem> CreateIssue(ArrayList<TrackingSystem> tracker){
String issueCreator;
String a = " ";
boolean is = true;
do {
System.out.println("*** Create an Issue***");
System.out.println("Describe your Issue: ");
issueCreator = in.nextLine();
}while (is);
TrackingSystem ts = new TrackingSystem(issueCreator,false);
tracker.add(ts);
return tracker;
}
Pay special attention to the loop condition: while(is). You declare bool is = true; but you never change it to false inside the loop. This means the loop will continue forever.
To fix this, you have to make some decisions. First, do you really want to continue looping here? Is your intention to allow the user to enter as many issues as they want? Or do you want to create only a single issue then return to the menu. If the former, then you need to figure out how the user will tell the program that they are finished entering issues. You can use this to stop the loop. If the later, then just remove the loop.
Now let's look at main():
public static void main(String[] args) {
ArrayList<TrackingSystem> tracker = new ArrayList<>();
Main myApp = new Main();
myApp.menu();
System.out.print("Select option >> ");
int option = in.nextInt();
switch (option){
case 1:
myApp.CreateIssue(tracker);
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Invalid choice...!");
break;
}
}
Even after you solve the problem with your code to create an issue, you will run the program and it will exit after one action. This is because you do not loop in main(). You need to add a loop here that repeats the following steps:
Print the menu.
Get the user's choice.
Perform the action for that choice
Repeat to step 1.
Each of these steps can be a method so that you can keep main() very short. Note how the first 3 steps are inside a loop. I think this is what you were trying to do with the loop for creating a new item, but somehow put the loop in the wrong place. As you can see here, by writing out the steps in words, we get a clear idea of how to organize the code. Doing this is a great tool when writing a computer program.
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();
.....
I am doing a project (based on a tutorial). I have a switch statement and for each case, there's a default in case the user input is invalid, and I write on the console "Sorry, I do not understand your request". However, if the user instead of writing whatever, writes "exit", the program should end without that "I don't understand request" sentence showing up.
This is stated in my IF statement in the beginning. What my current project does at the moment when I type "exit" is showing that line and then stopping. I don't understand how the program completely ignores that IF statement in the beginning.
public class MainGame {
public static GameSave gameSave = new GameSave();
public static String user = "";
public static Scanner scanner = new Scanner(System.in);
public static String question;
public static int relationshipPoints;
public static void main(String[] args) {
Random random = new Random();
question = gameSave.loadGame();
// relationshipPoints = gameSave.loadPoints();
RelationshipPoints points = new RelationshipPoints();
System.out.println("\n\t*** TEXT_GAME: FIRSTDATE ***\n");
System.out.println("-You can exit the game at any time by typing 'exit'.-\n\n");
while (true) {
if (user.equalsIgnoreCase("exit")) {
System.exit(1);
break;
} else {
switch (question) {
[...]
case "2":
switch (user = scanner.next()) {
case "1":
System.out.println("\n\nThe guy you met last night was nice. You want to "
+ "get back into contact with him. Why don't you check your phone for a number?");
question = "2A";
gameSave.saveGame("2A");
break;
case "2":
System.out.println("\n\n");
question = "0";
break;
default:
System.out.println("\nI do not understand your request.\n");
question = "2";
break;
}
break;
case "2A": [...]
Try replacing your while(true) {...} with while ((user = scanner.next() != null) { ... }
It looks like you are trying to access the "user" data without first setting it.
user = scanner.nextLine(); insert this line just after entering in while loop. your problem occurs as you are checking user equal to exit but user has nothing so control goes to else portion.
I have a homework assignment to create a class with a looping menu to manage a queue of cars. We learned queues in our last class.
My menu works perfectly fine until it catches InputMismatchException or QueueEmptyException, after which it goes into endless loop, not even stopping at the userInput.nextInt();. It works when it catches QueueFullException, but not the others.
My code is:
import java.util.*;
public class CarQueueManagement {
public static void main(String[] args) throws InputMismatchException, QueueFullException{
ArrayQueue queue = new ArrayQueue(3);;
Scanner userInput = new Scanner(System.in);
int carNum;
int choice = 0;
queue.add(1);
OUTER:
while (true) {
try{
System.out.println("ΜΕΝΟΥ:\n\t1. Άφιξη αυτοκινήτου");
System.out.println("\t2. Αναχώρηση αυτοκινήτου\n\t3. Κατάσταση ουράς\n\t4. Έξοδος");
System.out.print("\n\tΕπιλογή (1-4): ");
choice = userInput.nextInt();
switch (choice){
case 1:
System.out.print("\n\tΆφιξη αυτοκινήτου:\n\t\tΑριθμός Αμαξιού");
carNum = userInput.nextInt();
queue.add(carNum);
break;
case 2:
if(queue.isEmpty()){
System.out.println("\n\tΗ ουρά είναι άδεια, δεν χριάζεται διαγραφή.\n\n");
break;
}
String answer;
while(true){
System.out.print("\n\tΑναχώρηση αυτοκινήτου\n\t\tΕπιβεβαίωση; (y/n): ");
answer = userInput.next();
if(answer.equals("y")){
queue.remove();
break;
}
else if(answer.equals("n"))
break;
}
break;
case 3:
System.out.println("\n\tΚατάσταση ουράς:");
if(queue.isEmpty()) System.out.println("\t\tΗ ουρά είναι άδεια.\n\n");
else if(queue.isFull()) System.out.println("\t\tΗ ουρά είναι γεμάτη.\n\n");
else System.out.println("\t\tΗ ουρά έχει άδιες θέσοις.\n\n");
break;
case 4:
System.out.print("\n\nΕξοδος");
break OUTER;
default:
break;
}
}catch (InputMismatchException exc){
System.out.println("\t\tΛΑΘΟΣ ΕΙΣΑΓΩΓΗ\n");
}catch(QueueEmptyException exc){
System.out.println("\t\t" + exc.getMessage() + "\n");
}catch(QueueFullException exc){
System.out.println("\t\t" + exc.getMessage() + "\n");
}
}
}
}
From the intro section of java.util.Scanner docs (emphasis mine):
When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
Without the details, your while(true) loop is:
while (true) {
try{
choice = userInput.nextInt();
switch (choice){
case 1:
...
}
} catch (InputMismatchException exc){
// Do nothing.
}
}
When the user enters something that can't be converted to an integer, the Scanner throws an InputMismatchException, which you catch and ignore. Then the while loop goes back to the top, where it tries to execute userInput.nextInt()... but the Scanner is still looking at the same invalid input, so it immediately throws another InputMismatchException, which you catch and ignore again. Execution continues at the top of the while loop, where it calls nextInt() again... and the cycle continues forever.
You have to force the Scanner to skip the bad input, so your catch block should look something like this:
}catch (InputMismatchException exc){
System.out.println("\t\t[chastise the user in Greek]\n");
userInput.next(); // Skip invalid input.
}
Other Advice
As a general rule, lots of small methods are easier to understand than one large method. The nested while loops and switch statement were especially hard to follow. I was only able to find the bug by breaking that gigantic main method into many smaller, private static methods.
At the very least, each menu item could be handled in its own method. I also got rid of the break label by putting the whole menu into a separate method, which returned a boolean indicating whether the user was done or not. That reduced the whole loop inside main to:
boolean done = false;
while (! done) {
try{
done = handleUserInput(queue, userInput);
} catch (InputMismatchException exc) {
System.out.println("\nINPUT ERROR\n");
userInput.next();
} // Other catch blocks as before...
}
My handleUserInput doesn't do much --- it gets user input, determines which method should handle that input, and then returns true or false... It could be made simpler than this, too.
private static boolean handleUserInput(
final ArrayQueue queue,
final Scanner userInput
) {
boolean done = false;
printMenu();
int choice = userInput.nextInt();
switch (choice) {
case 1:
addToQueue(queue, userInput);
break;
case 2:
removeFromQueue(queue, userInput);
break;
case 3:
displayQueue(queue);
break;
case 4:
printExitMessage();
done = true;
break;
default:
break;
}
return done;
}
Splitting the various menu activities into separate methods made them much easier to follow. For example, when the logic was all mixed together in main, it was hard to tell if variables like carNum or answer were part of the problem. In this version, carNum is a local variable trapped inside the addToQueue method, so when I'm working anywhere else, I can completely ignore it.
I'm a beginner at Java and I want to get into it and I enjoy playing around with it. So I started doing an online course.
So after a few videos I learned a bit about switch statements and wanted to know how to loop them effectively.
package v1;
import java.util.Scanner;
public class Computer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Computer is booting up...");
System.out.println("Welcome to Mindows '93, please enter a command.");
String command = input.nextLine();
boolean computerON = true;
while (computerON) {
switch (command) {
case "!music":
System.out.println("Playing music!");
break;
case "!browse":
System.out.println("Launching browser...");
break;
case "!help":
System.out.println("Here are the commands that can be used !music, !browse, !shutdown");
break;
case "!shutdown":
System.out.println("Shutting down Mindows, goodbye!");
break;
default:
System.out.println("Command not recognised, type !help for a list of commands...");
break;
}
if (command.equals("!shutdown")) {
computerON = false;
}
}
}
}
So basically what I want is to make a mock text-based OS called Mindows with very limited functionality, but I'm having problems.
When I input !music, the program will constantly spam lines of "Playing music!"
When I enter !shutdown, however, it terminates which is what I want.
What I want is to type !music, !browse, !help and (x) to get the default message without the program spamming lines OR terminating.
I want to be able to type these commands in constantly until the !shutdown command is issued.
You read the command only once, out of your loop.
Try moving the line:
String command = input.nextLine();
into the while loop.
You're going into an infinite loop because you are accepting input from the user before the loop, and the input doesn't change during the execution of the loop. So if you entered "!music", the command doesn't change throughout the loop and the switch statement always goes into case "!music": in each iteration of the loop, which is why computerON is always true and the loop executes and prints "Playing music" infinitely.
The solution to this would be to move the String command = input.nextLine(); statement inside the while loop, like the above answers say.
Changed your logic here :
boolean computerON = true;
while (computerON) {
String command = input.nextLine();
switch (command) {
case "!music":
System.out.println("Playing music!"); break;
case "!browse":
System.out.println("Launching browser...");
break;
case "!help":
System.out.println("Here are the commands that can be used !music, !browse, !shutdown");
break;
case "!shutdown":
System.out.println("Shutting down Mindows, goodbye!");
break;
default:
System.out.println("Command not recognised, type !help for a list of commands...");
break;
}
if (command.equals("!shutdown")){
computerON = false;
}
}