Check whether switch case is chosen [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an exercise that using switch case. Assuming the code like
int choice;
do {
choice = //user input here;
switch (choice) {
case 1: //print something; break;
case 2: //print something; break;
case 3: //print something; break;
default: //print default; break;
}
} while(condition);
i want the user can only choose the case once. If they did choose case 1, they cannot choose that again.

Define a private bool variable for each one of your options and set it true if user called each one. Then check whether its true before running that option codes, again.
For example:
bool _case1=false;
int choice;
do{
choice = //user input here;
switch(choice){
case 1:
if(!_case1)
{
//print something;
_case1=true;
}
else
{
//Tell the user "You have selected this option once"
}
break;
//etc
}
}while(condition);

You could call methods for each case and have some bools that mark whether each case has already been chosen, use an if statement to check if the case has already been chosen and if so print a notice to pick another, otherwise perform the action.
You could also do this without separate methods but I am a fan of modular code. :)

I am assuming that a function that contains this switch case is called over and over again. If you want such a functionality, I would point to Set. Use the set to store the choices. If a set already contains a certain choice, take whatever action you deem fit.
Using a set is better than having a global array of booleans, since that could potentially be wasting a lot of memory, depending on the number of choices that you have.
Does that answer your question?

When user press the input
if the input is match case then
store this input in one List.
Next time you have to check this input.
If it belongs in List or not,
if belongs then case will not execute
if not belongs then it will execute the case.
Try in this way :
List<Integer> choiceList = new ArrayList<Integer>();
int choice;
do {
choice = //user input here;
if (choiceList.contains(choice)) {
continue;
}
choiceList.add(choice);
switch(choice) {
case 1: //print something; break;
case 2: //print something; break;
case 3: //print something; break;
default: //print default; break;
}
} while(condition);

As some of the other answers have said you can use a boolean to check if a case has been used or not. However, you can also use an int. The advantage of using an int is that you can specify how many times each case can be used. For example, the following code can only use each case once.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int choice;
int case1 = 0, case2 = 0, case3 = 0;
int case1lim = 1, case2lim = 1, case3lim = 1;
System.out.println("You may use may enter the number 1 " + case1lim + " times");
System.out.println("You may use may enter the number 2 " + case2lim + " times");
System.out.println("You may use may enter the number 3 " + case3lim + " times");
do {
System.out.println("Please enter a number between 1 and 3");
choice = user_input.nextInt();
if(choice == 1 && case1 < case1lim || choice == 2 && case2 < case2lim || choice == 3 && case3 < case3lim) {
switch(choice){
case 1: //print something;
case1++;
break;
case 2: //print something;
case2++;
break;
case 3: //print something;
case3++;
break;
default: //print default;
break;
}
} else {
System.out.println("Please pick another number since you have already used that case or you entered a bad value");
}
} while(true);
}
}
However if you change the values of the line
int case1lim = 1, case2lim = 1, case3lim = 1;
to
int case1lim = 2, case2lim = 1, case3lim = 1;
You can use the first case twice and all the other cases once.

Related

Scanner needs inputs twice before continuing

Hey guys i have got a small weird problem here, i am asking the user to input their menu choice and depending on what they choose it calls a certain method.
I have used scanner.next() after some googling but for some reason only when i enter 1 or 2, i press enter and then press say 1 again and then it actually works. But what is weird that it calls options 3, 4, 5 and 6, immediately without me having to input the number twice.
I have tried with scanner.nextLine() after the scanner.nextInt() and that just leaves me having to put my option 1 or 2 in with no result.
while(exit == 0)
{
System.out.println("\n");
System.out.println("Menu 1: Display fullname of the user \n");
System.out.println("Menu 2: Display of user information \n");
System.out.println("Menu 3: Change password \n");
System.out.println("Menu 4: List all of users in the library full name\n");
System.out.println("Menu 5: Search for a book\n");
System.out.println("Press 6 to search for a books location in the library\n");
System.out.println("Press 0 to exit\n");
System.out.println("Enter choice: ");
int menuChoice = scanner.nextInt();
scanner.next();
if(menuChoice == 1)
{
displayUserFullName();
}
else if(menuChoice == 2)
{
displayUserInformation();
}
else if(menuChoice == 3)
{
menuForChangePassword();
}
else if(menuChoice == 4)
{
displayAllUserInSystem();
}
else if(menuChoice == 5)
{
searchBookByISBN();
}
else if(menuChoice == 6)
{
searchBookLocation();
}
else if(menuChoice == 0)
{
exit = 1;
}
}
Thank you in advance!
int menuChoice = scanner.nextInt();
scanner.next();
Read the javadoc for scanner. It waits for user input:
public String next(): [..] This method may block while waiting for input to scan
So in your program, you say: wait for user to type and int, then wait for user to type something.
Remove the scanner.next(); and it should work.
Scanner is a class parsing single tokens, like nextInt, nextDouble, nextToken (String). With corresponding testing methods: hasNextInt and so on.
All this parsing you do not need, so use nextLine for an entered line, or an other Reader class (InputStreamReader, BufferedReader).
Also you may utilize switch instead of if else if.
String menuChoice = scanner.nextLine();
switch (menuChoice) {
case "1":
displayUserFullName();
break;
case "2":
displayUserInformation();
break;
case "3":
menuForChangePassword();
break;
case "4":
displayAllUserInSystem();
break;
case "5":
searchBookByISBN();
break;
case "6":
searchBookLocation();
break;
case "0":
exit = 1;
break;
default:
System.out.printf("Unknown choice: '%s'%n", menuChoice);
}
menuChoice will contain the entire line, without line ending.
You might use an int with Integer.parseInt(menuChoice) but this would throw a NumberFormatException on wrong input, aborting your program. Scanner.nextInt would hang too, actually needing an hasNextInt().

Repeating for loop in menu

I'm trying to create a hotel menu in Java (I'm still learning the language) and I've run into an issue. I can make the menu open a new menu, but when I make a choice from that second menu, it constantly loops. I think it's the for loop that is causing the issue. Can anyone advise how I get the second menu entry to stop looping? Methods below:
Menu class method:
public void getMenu()
{
Floor floor = new Floor();
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Booking Menu");
System.out.println("Select from the options below");
System.out.println("1. Check room availability");
System.out.println("2. Display floor");
System.out.println("3. Display all availability");
System.out.println("4. Cancel Booking");
System.out.println("Please enter choice (press 8 to continue)");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: room.getRoomMenu();
break;
case 2:
break;
case 3:
break;
}
}
while (choice !=8);
}
That menu opens a second menu in this method:
public void getRoomMenu()
{
Floor f1 = new Floor(1);
Floor f2 = new Floor(2);
Floor f3 = new Floor(3);
Floor f4 = new Floor(4);
boolean check = false;
Scanner kboard = new Scanner(System.in);
int choice = 0;
System.out.println("Which Floor?");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
choice=kboard.nextInt();
do
{
switch(choice)
{
case 1: f1.displayFloor();
break;
case 2: f2.displayFloor();
break;
case 3: f3.displayFloor();
break;
case 4: f4.displayFloor();
break;
}
}
while(choice !=8);
kboard.close();
}
The second menu option should display the chosen floor which displays all rooms on that floor. This is the displayFloor method:
public void displayFloor()
{
/**
* Displays floor number and room display method
*/
System.out.println("Floor: "+floorNumber);
for(int counter=0;counter<rooms.length;counter++)
{
rooms[counter].display();
}
}
Both your while loops continue looping as long as choice != 8. And since you never modify the choice inside the loop, it will just continue looping (unless 8 was input by the user).
Also note that the break; you added are breaks for the switch-case, not to stop the do-while-loop. To have a break within the switch-case stop the entire do-while-loop, you should use a label to give the loop a name, and break that one. In addition, you should ask the user to give a new input if it didn't came into one of the switch-cases, otherwise it will still loop forever. So something like this:
choice = kboard.nextInt();
myLoop: do {
switch(choice) {
case 1:
f1.displayFloor();
break myLoop;
case 2:
f2.displayFloor();
break myLoop;
case 3:
f3.displayFloor();
break myLoop;
case 4:
f4.displayFloor();
break myLoop;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
choice = kboard.nextInt(); // Ask the user for a new input
break; // <- This break only breaks the switch, not the loop
}
} while(choice !=8);
If your intention was to continue looping until the user input 8, it should be something like this instead:
choice = kboard.nextInt();
do {
switch(choice) {
case 1:
f1.displayFloor();
break;
case 2:
f2.displayFloor();
break;
case 3:
f3.displayFloor();
break;
case 4:
f4.displayFloor();
break;
default: // Not one of the above
System.out.println(choice + " is an unknown choice. Please choose again.");
}
choice = kboard.nextInt(); // Ask the user for a new input for the next iteration
} while(choice !=8);
The loop is occurring here:
while(choice !=8);
You need to make sure that the ending condition is always satisfied at some point to avoid unwanted infinite loops.
Maybe you meant if(choice != 8) rather than a do/while loop (which will keep running until choice is 8, which will only occur if the user inputs 8).

Why does System.out.println(String) not print anything?

I have some code in my java IDE and I believe that it has support for console. I have used java before and know the ins and outs. However, this problem has not occured with me before. My code looks like this:
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
System.out.println("Choose a class.");
TimeUnit.SECONDS.sleep(10);
System.out.println("Press 1 for the a class.");
TimeUnit.SECONDS.sleep(10);
System.out.println("Press 2 for the b class.");
TimeUnit.SECONDS.sleep(10);
System.out.println("Press 3 for the c class.");
TimeUnit.SECONDS.sleep(10);
switch(choice) {
case 1:
playerClass.chosenClass = "a";
break;
case 2:
playerClass.chosenClass = "b";
break;
case 3:
playerClass.chosenClass = "c";
break;
default:
System.out.println("Null class. Please press 1-3 to choose a player class.");
}
}
I have all the imports, and the playerClass class does exist. The problem is, the "System.out.println(String)"'s do not work.
You're printing the prompt after accepting the input. And as you haven't seen the prompt yet, you probably aren't typing any input. So you never get past Scanner.nextInt().
Your code doesn't make sense.
What you might want to do is set your logic more like:
System.out.println("Press 1 for xx, 2 for xx, or 3 for xx");
if(scanner.hasNext()){
choice = scanner.Int();
}
if(choice == 1){
//do whatever;
}
else if(choice == 2){
//do whatever;
}
I might not be understanding your question right but I think you need to make sure you keep everything in order.

Java program doesn't have any output when using a switch statement inside a while loop?

So I need the statements inside the while loop to repeat until the user enters 4 (which exits the program), but when I try to run the program, nothing is outputted to the screen (but it compiles just fine). Why would it do this? This answer is probably really simple, but any help would be really appreciated!
public class Driver
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int answer;
boolean bool = true;
while(bool);
{
System.out.println("\n\tGeometry Calculator\n" +
"\t1. Calculate the Area of a Circle\n" +
"\t2. Calculate the Area of a Rectangle\n" +
"\t3. Calculate the Area of a Triangle\n" +
"\t4. Quit\n");
System.out.print("\tEnter your choice (1-4): ");
answer = keyboard.nextInt();
switch(answer)
{
case 1:
System.out.println("\n\tCalculating the area of a circle...");
break;
case 2:
System.out.println("\n\tCalculating the area of a rectangle...");
break;
case 3:
System.out.println("\n\tCalculating the area of a triangle...");
break;
case 4:
System.out.println("\n\tQuiting...");
System.exit(0);
break;
default:
System.out.println("\n\tPlease enter a number between 1 and 4.");
}
if(answer == 4)
bool = false;
}
}
You have one tiny mistake. You have added ; after the while loop. Just delete it. Your code should be
while(bool)

How would I create a "infinite" loops until the user decides to call it quits?

I'm having a slight problem.
I have a menu asking to:
reroll
get val
show max
show min
when the user chooses an option I want it to do one of them THEN re ask the menu in a sort of inifinite loop:
code:
import java.io.InputStream;
import java.util.Scanner;
class RecordDice {
public static void main(String[] args){
int dSides, Sides, Choice;
int max, min;
Scanner s = new Scanner(System.in);
Scanner c = new Scanner(System.in);
System.out.println("How many sides should the dice have?");
Sides = s.nextInt();
if(Sides == 4 || Sides == 6 || Sides == 12 || Sides == 20 || Sides == 100){
System.out.println("Please make a choice:\n" +
"1 - reroll the dice\n" +
"2 - get the value\n" +
"3 - show the maximum\n" +
"4 - show the minimum");
} else {
System.exit(-1);
}
Dice2 d = new Dice2(Sides);
int Choice = c.nextInt();
int Value = d.getValue();
switch(Choice){
case 1:
System.out.println();
d.reroll();
break;
case 2:
System.out.println("The current value is " + Value);
break;
case 3:
System.out.println("The maximum is " );
break;
case 4:
System.out.println("The minimun is ");
break;
}
}
}
Would putting the menu in a method and just calling the method every time a option is picked?
You can use a while loop to keep displaying it.
boolean keepGoing = true;
While(keepGoing)
{
//your code
}
Then to end it ask the user if they want to end it an set the boolean to false.
Add "5 - quit" to your menu.
Create a boolean, something like exit, initialized to false.
Add case 5: exit = true; break;
Then wrap the whole thing in while(!exit)
boolean exit = false;
while(!exit) {
//all the code you already have, starting with:
System.out.println("How many sides should the dice have?");
//and ending with the switch statement
//Plus the addition to the menu and addition to the switch statement
}
Ordinarily, I would do something like:
while(true) {
//do stuff
if(someExitCondition) {
break;
}
}
But seeing how as you're handling your user input with a switch statement, my above suggested method seems to be the cleanest way of handling it in this scenario.
Wrap it all in a do-while loop.
boolean userWantsToQuit = false;
do {
// code
// evaluate userWantsToQuit…
} while (!userWantsToQuit);
boolean keepGoing=true;
while(keepGoing)
{
//user input
if(user input to exit)
{
keepGoing=false;
}
}
or
while(true)
{
//user input
if(user input to exit)
{
break;
}
}
Assuming selection of dice sides you will allow only once, put code below that in do while loop.
You may prompt user "Do you wish to continue" after your switch block.
Get that value scanned
Condition in while loop will be something list while("YES".equals(userInput)).. assuming user will input YES or NO strings.

Categories