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.
Related
I am writing a menu driven program to perform operations on either of the two stacks Stack1 or Stack2. I am using a switch case to accept user's choice. Suppose if user chooses Stack1 and Case 1 is going to be executed. So inside Case 1 can I create another switch case to ask user's choice to perform push or pop operation.
Is it possible to create nested switches in a java program?
we can write nested switch in java
option=Some user input (scan.nextInt())
`switch(option)
{
case 1:
option2=//some user input
switch(option2){
case 1:
enter code here;
break;
case 2:
enter code here;
break;
//soon
}
break; // Case1 break in first switch case
case 2:
option2=//some input
switch(option2){
case 1:
enter code here;
break;
case 2:
enter code here;
break;
//soon
}
break; // Case2 break in first switch case
default:
break;
Likewise we can nested switch case in java
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?
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;
}
}
I am trying to make a switch that will step through the code like in Javascript by adding "jedi++" at the end but it won't let me do that any suggestions on how I can accomplish that? Here is a snippet of the code.
switch(jedi){
case 1:
while(!input.equalsIgnoreCase("guardian") && !input.equalsIgnoreCase("sentinel") && !input.equalsIgnoreCase("consular")){
System.out.println("Please enter the path followed by this Jedi.");
System.out.println("(Guardian, Sentinel or Consular)");
}
registrant.setPath(input);
break;
case 2:
while(!input.equalsIgnoreCase("master") && !input.equalsIgnoreCase("knight") && !input.equalsIgnoreCase("padawan")
&& !input.equalsIgnoreCase("youngling")){
System.out.println("Please enter the Jedi's Rank.");
System.out.println("(Master, Knight, Padawan, Youngling)");
input = keyboard.nextLine();
}
registrant.setRank(input);
break;
jedi++;
}
Do you want to jedi++ in all the cases or just in case 2?
If it's just for case 2, you could do
case 2:
....
jedi++;
break;
case 3:
....
if it's for all the cases, you could do jedi++ after the switch block.
Statements can exist only within the case. since jedi++ is not part of case, its throwing error. Putting the increment statement under required case statement will solve the issue.
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.