Java switch/case going to default after case [duplicate] - java

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I'm trying to work on my homework for class, and I'm using a switch case to make a command line interface, but I'm having a problem with the part I'm using. When I execute the addCard command, it goes through fine, but then afterwards goes to the default section. When I try using any of the other sections, or use it without the try segment, it works and doesn't go to default. Any thoughts on how to repair this? Code below
public static void cmdLine(String Cmd) {
switch(Cmd) {
case "Help":
case "?":
System.out.println("Available Commands:\naddCard = Add a card!\ndeleteCard = Delete a Card!\nfindCard = Locate Card Number by Name!\nCard (Card Number) = Work with your card");
break;
case "addCard" :
System.out.println ("Enter Account Name:");
String cName = scan.nextLine();
try {
System.out.println ("Enter Account Start Balance:");
int cBal = scan.nextInt();
System.out.println ("Enter Account Number:");
int cNum = scan.nextInt();
PPArray.addCard(cName, cBal,cNum);
} catch (InputMismatchException nfe) {
System.out.println("InputMismatchException: Please try again with only the card number. (Ex. 12345");
break;
}
break;
case "deleteCard" :
System.out.println("here we will have a command to remove the card from the array");
break;
case "Card" :
System.out.println("This will lead to a new function to operate with said card");
break;
case "Exit":
case "exit":
case "Quit":
case "quit":
return;
default :
System.out.println("Invalid Command ('?' or 'Help' for commands)");
System.out.println(PPArray.cardArray[1].name);
}
cmdLine(scan.nextLine());
}

When you run the try block in "addCard", you get input with int cNum = scan.nextInt();.
Then, when you call cmdLine(scan.nextLine()); after the switch statement, it consumes the new line, which causes the default clause to be called.
You can prevent this by adding scan.nextLine() at the end of that try block.
case "addCard" :
System.out.println ("Enter Account Name:");
String cName = scan.nextLine();
try {
System.out.println ("Enter Account Start Balance:");
int cBal = scan.nextInt();
System.out.println ("Enter Account Number:");
int cNum = scan.nextInt();
PPArray.addCard(cName, cBal,cNum);
scan.nextLine();
} catch (InputMismatchException nfe) {
System.out.println("InputMismatchException: Please try again with only the card number. (Ex. 12345");
break;
}
break;
BTW, I think it is bad coding to recursively call cmdLine(scan.nextLine()); in order to process the next input. I think a while loop would make more sense.

You have to actually exit the program if you want it to quit:
case "Exit":
case "exit":
case "Quit":
case "quit":
return;
should be
case "Exit":
case "exit":
case "Quit":
case "quit":
System.exit(0);
What is the next line?
cmdLine(scan.nextLine());
Is reading something that doesn't match any of the cases, your step debugger will show you where your logic error is. Step debugging is a much more valuable skill than System.out.println() and guessing.

change this
case "Exit":
case "exit":
case "Quit":
case "quit":
return;
to
case "Exit":
case "exit":
case "Quit":
case "quit":
break;
EDIT:
One more little issue is cmdLine(scan.nextLine()); taking new line each time and causing default to execute. Better to use cmdLine(scan.next()); which do not accept multiple words or line.

Related

Clearing the console screen to accept a new value from the user

Hi please in a switch case program that I am developing, I am using a do..while loop to handle the case when a user enters a value that does not meet the condition but got stuck with what I should put in the "while" brackets as an error is shown on the "while" line..
package assignment;
import java.util.*;
public class Assignment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("1)Monday\n2)Tuesday\n3)Wednesday\n4)Thursday\n5)Friday\n6)Saturday\n7)Sunday");
System.out.println("");
int day = input.nextInt();
System.out.println(" ");
do {
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Oh oh, that's not an accepted number, kindly try again");
break;
}
for (int clear = 0; clear < 1000; clear++) {
System.out.println("\b");
}
} while (!(day.equals("1") || day.equals("2") || day.equals("3") || day.equals("4") || day.equals("5") || day.equals("6") || day.equals("7")));
}
}
Instead of checking day as a String, simply check it as an integer which it already is. No need to allocate extra memory when creating a new String to check with an integer.
When you begin your while loop, it seems that there is no way to check for new input. How would you be able to get new input EACH time in your loop?
There is no reliable way to clear your console cross platform as depending on the IDE you are using or which terminal UNIX or PowerShell or CMD. Take a look at this answer Java: Clear the console
Since this seems like a homework assignment, I suggest that you think about how your while loop conditions could be simplified.
Hint: Is there any way to check a range of numbers? What if you had to check 1000 different numbers, would you check each number with OR conditions?

Trying to use a For-Loop with a 'menu'

Beginner here, please be as explanatory as possible!
A course question asked me to create a menu (done).
Have multiple option on the menu give different one-time result (done).
Now it wants me to implement a for, while and do...while loop (CANNOT UNDERSTAND)
I have genuinely tried all of my rudimentary knowledge, including creating and populating an array inside the for loop (which in hindsight was a stupid idea).
public void displayMenu()
{
System.out.println("A. Option #A");
System.out.println("B. Option #B");
System.out.println("C. Option #C");
System.out.println("D. Option #D");
System.out.println("X. Exit!");
System.out.println();
System.out.println("Please enter your choice:");
}
public void start()
{
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
public void startFor()
{
/*Each of these methods will modify the original start() method, each
*will add a loop of the specific type so that the menu is displayed
*repeatedly, until the last option is selected. When the last option
*is selected, exit the method (i.e. stop the loop).
*/
}
As you asked for an example with for in the comments.
The point of the exercise seems to be to iterate on the menu until an exit condition is met ("X".equals(input)). That means than between the three conditions in the for statement, that's the only one you need to specify. This is because the general form of a (basic) for statement is
for ( [ForInit] ; [Expression] ; [ForUpdate] )
Where none of those terms between brackets are mandatory, so we can as well get rid of [ForInit] and [ForUpdate] (but keeping the semicolons). This has the effect of not initializing anything with [ForInit] and doing nothing at the end of each iteration of the loop with [ForUpdate], leaving us only checking for the exit condition that is given by the [Expression] expression (when it's evaluated to false, the loop exits).
Notice that the console is declared outside the loop, since it would be wasteful to allocate one at each iteration. And also input, since you need it in the for statement's condition.
Scanner console = new Scanner(System.in);
String input = "";
for (;!"X".equals(input);) { // notice, the first and last part of the for loop are absent
displayMenu();
input = console.nextLine().toUpperCase();
System.out.println();
switch (input) {
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
}
You may notice this is a bit awkward, as this is not what you usually use a for loop for.
Anyway, at this point, the while version becomes trivial (while (!"X".equals(input))) and, in this case, the do...while is equivalent as well, (do { ... } while (!"X".equals(input))) as the same condition applies both at the end of the current loop and at the beginning of the next one, and there are no side effects between them.
As an aside, you may notice that while (condition) and for (; condition ;) are functionally equivalent and you may wander why you should use one instead of the other. The answer is readability. It's a lot more clear what you want to do when you do while (condition).
All arguments in for loop is not mandatory.
Define a stopflag and check whether is input is "X" or not.
Whenever input is "X" just change stopFlag or just simply you can break loop using break statement;
public void startFor()
{
boolean stopFlag = false;
for(; stopFlag == false ;) {
displayMenu();
Scanner console = new Scanner(System.in);
String input = console.nextLine().toUpperCase();
System.out.println();
switch (input)
{
case "A": System.out.println("Option #A was selected"); break;
case "B": System.out.println("Option #B was selected"); break;
case "C": System.out.println("Option #C was selected"); break;
case "D": System.out.println("Option #D was selected"); break;
case "X": System.out.println("You chose to Exit"); break;
default: System.out.println("Invalid selection made"); break;
}
if(input.contentEquals("X"))
stopFlag = true;
}
}

How to use switch case in java such it accepts the character without pressing enter?

Hi I am new to stackoverflow.com I have been using JAVA recently from programming purposes. I have a code using switch case which works fine. This is the code:-
Scanner s=new Scanner(System.in);
int i=1;
while(i>0)
{
char key = s.next().charAt(0);
switch(key)
{
case 'w':
System.out.println("I am moving forward");
break;
case 's':
System.out.println("I am moving backward");
break;
case 'd':
System.out.println("I am moving right");
break;
case 'a':
System.out.println("I am moving left");
break;
case 'x':
i=-1;
break;
default:
System.out.println("Plz give a valid command");
}
}
But the problem is every time I give an input command I have to press enter so that the program accepts the input. I want a method for which the program should accept the command as soon as I give the input character. Any tips please???
I think that, you must handle the Keyboard events like keyTyped(KeyEvent e){} instead of Scanner(System.in);. You can do it by implementing the KeyListener interface.

switch with while loop won't end when told to

I have two methods, getOption() and driver().
getOption() takes a String from a scanner, breaks it into individual words, and returns an array of Strings.
driver() then gets the first value of that array, getOption()[0], and begins a while loop based on that first String. While the String does not equal "quit", check if the value matches any switch case. However, when I run it, it can do any of the switch cases, but the quit statement never works. Can anyone give me a hand?
public String[] getOption(){
String optionLine[];
Scanner input = new Scanner(System.in);
System.out.println("Input string\n");
String line = input.nextLine();
optionLine = line.split(" ");
return optionLine;
}
public void driver(){
String option = getOption()[0];
Stats s = new Stats(data);
while (!"quit".equals(option)){
switch (option) {
case "add": //data.put(getOption()[1], getValues());
System.out.println("add");
break;
case "set": System.out.println("set");
break;
case "print": System.out.println(Arrays.toString(data));
break;
case "sum": System.out.println(s.sum());
break;
case "mean": System.out.println(s.mean());
break;
case "stdev": System.out.println(s.standardDeviation());
break;
case "median": System.out.println(s.median());
break;
case "primes": System.out.println(s.primes());
break;
case "summary": System.out.println("summary");
break;
//case "test": System.out.println(Arrays.toString(getValues()));
}
driver();
}
}
You are calling recursively at the end of your while loop the method driver();
no matter if you read getOption or not, you are still coming back inside the method...
that is the reason of the apparently not working while condition...
a very unusual pitfall.
Once you get into your While loop, you never change the value of option. You could change your while to be
while (true){
option = getOption()[0];
Stats s = new Stats(data);
switch (option) {
case "add": //data.put(getOption()[1], getValues());
System.out.println("add");
break;
case "set": System.out.println("set");
break;
case "print": System.out.println(Arrays.toString(data));
break;
case "sum": System.out.println(s.sum());
break;
case "mean": System.out.println(s.mean());
break;
case "stdev": System.out.println(s.standardDeviation());
break;
case "median": System.out.println(s.median());
break;
case "primes": System.out.println(s.primes());
break;
case "summary": System.out.println("summary");
break;
//case "test": System.out.println(Arrays.toString(getValues()));
case "quit": break;
}
}
Note, if you use my answer, you will need to no longer recursively call driver().
You don't seem to be changing the value of option anywhere. You're calling driver() recursively, but that doesn't affect the local variable in the currently executing method which stays the same.
So, one driver() method calls another, which creates its own option variable, unrelated to the option variable of the caller. Basically, only the innermost call to driver() will ever return and you'll be stuck in the while loop of its caller.
Get rid of that recursion, it's unnecessary. Under the switch just call getOption() and update the value of option.
while (!"quit".equals(option)){
// switch statement
option = getOption()[0];
}

Loop a Switch case

I'm attempting to write code for a user menu. Put simply the user is given a menu of 5 options to input exam scores. Each option runs a method from a class. Once the method is done it will prompt the menu once more, and continue to loop until the user selects option 5, which will terminate the program. Though I am not sure how I can get this switch case to loop.
prof1.menu();
choice = console.nextInt();
do
{
switch(choice)
{
case 1: prof1.inputExamScore();
break;
case 2: prof1.modifyExam();
break;
case 3: prof1.displayExamScores();
break;
case 4:
case 5:
default:
System.out.println("That is not a valid input.");
}
}while (choice < 1 || choice > 4);
You can try infinite loop where you can break it from switch block as shown below:
Sample code :
loop: while (true) {
switch (choice) {
case 1:
...
case 5:
break loop;
default:
System.out.println("That is not a valid input.");
}
}
Hint:
increment a counter for a valid input and break the loop if 5 is chosen after accepting all valid inputs
move the code for accepting the user input in the loop at the beginning.

Categories