How can I loop a case switch statement if an invalid value is chosen i.e the default

switch case with if else in java
switch case with do you want to continue in c
switch case in c
switch case java
do you want to continue in switch case in java
while loop with switch case in java
switch statement example
switch statement accepts in c

Here is an example where a menu of values is available. i would like to have it loop back to the start if none of the options are chosen.

static void Main(string[] args)
{
    Console.WriteLine("1 : Option 1");
    Console.WriteLine("2 : Option 2");
    Console.WriteLine("3 : Option 3");
    Console.WriteLine("4 : Option 4");
    Console.WriteLine("5 : Option 5");
    Console.Write("Please enter your option choice: ");
    string choice = Console.ReadLine();

    int intChoice = int.Parse(choice);
    switch (intChoice)
    {
        case 1:
            Console.WriteLine("you chose 1");
            break;
        case 2:
            Console.WriteLine("you chose 2");
            break;
        case 3:
            Console.WriteLine("you chose 3");
            break;
        case 4:
            Console.WriteLine("you chose 4");
            break;
        case 5:
            Console.WriteLine("you chose 5");
            break;
    }
}

I've tried to do it through using classes and method, but i just got really confused.

thank you in advance for any help.

Wrap the whole thing in a do-while block:

bool isValid = true;

do
{
    isValid = true;
    // Write to console
    // read from console
    switch(intChoice)    
    {
        // Place some cases here.
        default: 
            Console.WriteLine("Invalid Choice")
            isValid = false;
    }
}
while(!isValid);

Is a default case necessary in a switch statement?, Which of the following control statement is used to terminate the loop next switch break with? Note that the entire body of switch is just one long statement with labels in it. It works as any other statement, once you entered it through one of the labels. Just like an ordinary C++ statement will not "loop back" for you by itself unless you make it a cycle or use goto, neither will the body of switch "loop back" for you by itself.

Use a boolean value as a flipswitch that tell the while loop to continue running or not. Here's a small example:

bool stillRunning = true;

while (stillRunning)
{
    Console.WriteLine("Enter a number.");
    string input = Console.ReadLine();
    int key = Convert.ToInt32(input);

    switch (key)
    {
        case 1:
            // Do something.
            stillRunning = false;
            break;

        case 2:
            // Do something.
            stillRunning = false;
            break;

        default:
            Console.WriteLine("No key selected.");
            break;
    }
} 

Learn switch, break and continue in C, How can I loop a case switch statement if an invalid value is chosen i.e the default Use a boolean value as a flipswitch that tell the while loop to continue running or not. Here's a small ToInt32(input); switch (key) { case 1: // Do something. stillRunning = false; break; default: Console.WriteLine("No key selected."); break  this reference has more switch examples and also covers the falling through case as well. As Steve suggested it also probably makes more sense to have the return after the while statement. This is would be the expected control flow and will most likely be easier to maintain as well.

you can use default

    switch (intChoice)
    {
        case 1:
            Console.WriteLine("you chose 1");
            break;
        case 2:
            Console.WriteLine("you chose 2");
            break;
        ....... 
        default: 
            //your logic here
            break;
    }

it is your choice after that how you like to do it. you can use a while and a Boolean value like this:

static void Main(string[] args)
        {

            Console.WriteLine("1 : Option 1");
            Console.WriteLine("2 : Option 2");
            Console.WriteLine("3 : Option 3");
            Console.WriteLine("4 : Option 4");
            Console.WriteLine("5 : Option 5");
            Console.Write("Please enter your option choice: ");


            bool correct = true;

            while (correct)
            {
                string choice = Console.ReadLine();
                int intChoice = int.Parse(choice);
                switch (intChoice)
                {
                    case 1:
                        Console.WriteLine("you chose 1");
                        break;
                    case 2:
                        Console.WriteLine("you chose 2");
                        break;
                    case 3:
                        Console.WriteLine("you chose 3");
                        break;
                    case 4:
                        Console.WriteLine("you chose 4");
                        break;
                    case 5:
                        Console.WriteLine("you chose 5");
                        break;
                    default:
                        correct = false;
                        break;
                }
            }
        }

Using continue in a switch statement, The switch statement evaluates its expression, in this case the value of month , and break; default: numDays = 0; break; } System.out.println("Number of Days  An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value. Also, the value provided to each case statement must be unique. Another point of interest in the switch statement is the break statement after each case.

Thus you need only one number, it's better to use GetKey method, then reading string value from console and then parsing it to int:

DisplayOptions();
bool choiceDone;

do
{
    choiceDone = true;

    switch(GetChoice())
    {
       case ConsoleKey.D1:
           Console.WriteLine("you chose 1");
           break;
       case ConsoleKey.D2:
           Console.WriteLine("you chose 2");
           break;
           // etc
       default:
           choiceDone = false;
           break;
    }

} while(!choiceDone);    

Also I have extracted several methods, to make code more clean:

private ConsoleKey GetChoice()
{
     Console.Write("Please enter your option choice: ");
     return Console.ReadKey().Key;
}

private void DisplayOptions()
{
     Console.Clear();
     Console.WriteLine("1 : Option 1");
     Console.WriteLine("2 : Option 2");
     Console.WriteLine("3 : Option 3");
     Console.WriteLine("4 : Option 4");
     Console.WriteLine("5 : Option 5");
}

if, else and switch in Java, Learn switch, break and continue in C. Learn to break a loop whenever you want. default: statement(s); }. In switchcase , the value of expression enclosed case 'F': printf("You failed\n"); break; default: printf("Invalid grade\n"); } return 0; } the loop whereas continue statement passes control to the conditional test i.e.,​  When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached. A switch statement can have an optional default case, which

public void GetInput()
{
    int inputValue = 0;
    bool isValidInput = false;
    List<int> validEntries = new List<int> { 1,2,3, 42, 55, 69};

    while (!isValidInput)
        isValidInput = int.TryParse(Console.ReadLine(), out inputValue) && validEntries.Contains(inputValue);

    switch (inputValue)
    {
        case 1:
            {
                // something
                break;
            }
        case 2:
            {
                // something else
                break;
            }
        default:
            {
                //yet something else
                break;
            }
    }
}

Edit: Added explicit value check instead of accepting any integer.

The switch Statement, This type of decision taking is done using if statement in Java. therefore the statement in the body of else i.e. 'System.out.println("a is greater than b");' will be executed. If it is false, then the condition of else if is checked and if that is also wrong, default: statement(s); }. In switchcase, value of the expression enclosed in  Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

switch, The switch statement evaluates an expression, matching the (If multiple case s match the provided value, the first case that matches is selected, even if the case s If no default clause is found, the program continues execution at the Edge Full support 12, Firefox Full support 1, IE Full support 4, Opera  You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon. The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

Structured Programming with C++, The switch statement will then check the variable iOpt. If it is 1, the statements after “case 1” are executed. There we check which of the two numbers are the  Implementation of Switch statement in Python. As we know, the switch case statement and if-else-if ladder statement are alternate to each other. Both can be used to achieve the same purpose, but a switch case statement provides better performance and more manageable code than an if-else-if ladder statement.

Oswaal CBSE Question Bank Class 12 Informatics Practice , Identify invalid variable names out of the following. (i) and (ii)? (i) t = 2; (ii) if (t = =2) d = 3; [OD 2016] Ans. (i) t is a variable assigned a value 2. (ii) It is a conditional statement if t == 2 true then d=3. Help him in writing suitable Java statement to extract selected item from a given getText()); switch(ch) { case 1: jTextField2. The default case. The default case specifies the switch section to execute if the match expression doesn't match any other case label. If a default case is not present and the match expression doesn't match any other case label, program flow falls through the switch statement. The default case can appear in any order in the switch statement.

Comments
  • That's not how switch statements work. You'll have to wrap the whole thing around a while or for loop
  • As an aside (and as shown in Heather's example below) you might want to consider using int.TryParse to check that 'choice' can indeed be converted to an int. You could continue to use int.Parse, but would have to wrap it in a try/catch block - right now an invalid choice could terminate the app with an unhandled exception.
  • After first invalid input, flag will be set to false, you need to set it back to true on every loop
  • Awesome. Thank you for the help.
  • this is sort of what i tried with the methods, but i'm still not sure how to actually use this. or understand the key part.
  • You can read about Console.ReadKey on msdn msdn.microsoft.com/en-us/library/system.console.readkey.aspx Also you are free to ask about methods. What is not clear to you?
  • do i have to put them into a class to call them? when i've been trying with the code you used as an example i get an error asking for a reference.
  • @n00blearner put first code block into Main method. Then paste other two methods under your Main method (inside Program class). And last step - add word static to both methods definition. Like this: private static void DisplayOptions()
  • What if I enter 42? :)