Yasin
Yasin

Reputation: 43

Looping back after condition is false

int userSelection;
string userInput;
Console.WriteLine("Welcome! Please make a selection by Entering 1, 2, 2 or 4");
DisplayMenuOptions();
userSelection = int.Parse(Console.ReadLine());

while (userSelection >= 1 && userSelection <= 4)
{
if (userSelection == 1)
{
    // CODES FOR FULL FILE LISTING"
}
else if (userSelection == 2)
{
    // CODES FOR FILTERED FILE LISTING"
}
else if (userSelection == 3)
{
    // CODES FOR DISPLAY FOLDER STATISTICS"
}
else if (userSelection == 4) //code that will be executed every time user select 4
{
    // CODES TO QUIT"
}
else 
{
     Console.WriteLine("ERROR MESSAGE HERE");
}
Console.WriteLine("Press Enter to Continue"); //waits for user to press enter
Console.ReadKey(); //reads user keystroke
Console.Clear(); //clears display information
DisplayMenuOptions();
userSelection = int.Parse(Console.ReadLine()); //reads and converts user selection
}

but it quits the application instead of waiting for user to input again.

I am a beginner at programming and this is my first attempt at any Console C# Application. It is part of my assignment. Therefore if there is anything I am doing wrong here please guide me.

When I place it outside of the while loop it only executes once when user enters invalid input but it quits the second time the user enters invalid output.

Thank you

Upvotes: 2

Views: 287

Answers (2)

Jonathan Wood
Jonathan Wood

Reputation: 67193

The problem is your while condition prevents the loop from being entered when the selection is invalid.

You need to remove this behavior if you want to detect invalid values inside the loop.

while (true)
{
    if (userSelection == 1)
    {
        // CODES FOR FULL FILE LISTING"
    }
    else if (userSelection == 2)
    {
        // CODES FOR FILTERED FILE LISTING"
    }
    else if (userSelection == 3)
    {
        // CODES FOR DISPLAY FOLDER STATISTICS"
    }
    else if (userSelection == 4) //code that will be executed every time user select 4
    {
        // CODES TO QUIT"
    }
    else 
    {
         Console.WriteLine("ERROR MESSAGE HERE");
         break;
    }
    Console.WriteLine("Press Enter to Continue"); //waits for user to press enter
    Console.ReadKey(); //reads user keystroke
    Console.Clear(); //clears display information
    DisplayMenuOptions();
    userSelection = int.Parse(Console.ReadLine()); //reads and converts user selection
}

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151594

Because that's what your while loop says: "loop while the input is between 1 and 4" , which becomes false when the user enters invalid input.

Given you only want to exit when the input equals four, nothing else:

while (userSelection != 4)

Then you can restore the } else { too, as that did work as intended.

Upvotes: 6

Related Questions