• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.
  • The forums have been upgraded with support for dark mode. By default it will follow the setting on your system/browser. You may override it by scrolling to the end of the page and clicking the gears icon.

C# looped if statements

Joined
Jul 6, 2006
Messages
666 (0.10/day)
Location
England, UK
Processor AMD Athlon 3800+ X2
Motherboard ASUS A8N-SLI SE
Cooling 2 Exhaust fans
Memory 2x512MB DDR400 RAM
Video Card(s) Connect3D ATI Radeon X1900XT 512MB
Storage 80GB Maxtor DiamondMax
Display(s) Packard bell 17" CRT
Case Stock
Power Supply 580W Hiper Type-R
Hi folks, ive just begun programming and im having trouble with looping the result of an if else statement, basically my code looks like this:


Console.Clear();

Console.Write("Please enter your catagory: ");
string = Console.ReadLine();

if (string == "A" || string == "a");
{
Console.Write("You entered A");
}
else if (string == "B" || string == "b");
{
Console.Write("You entered B");
}
else if (string == "C" || string == "c");
{
Console.Write("You entered C");
}
else
{
Console.Write("You have not entered a valid catagory");
Console.Write("\nPress enter to re-enter...");
}


I tried entering a do while but in the while condition i didnt know what to put so that it loops the result of the else, i want it to loop from the clear so that the person can re-enter there catagory if the else statement is activated. Thanks for any help/advice :respect:
 
Use a while statement.
Assume "X" is your exit condition.
Code:
While (string != "X")
{
    Do something
}
 
He could also use a break statement to do what he wants. (Though it doesn't really matter...)

Code:
While (1)
{
   Console.Clear();

   Console.Write("Please enter your catagory: ");
   string = Console.ReadLine();

   if (string == "A" || string == "a");
   {
      Console.Write("You entered A");
      break;
   }
   else if (string == "B" || string == "b");
   {
      Console.Write("You entered B");
      break;
   }
   else if (string == "C" || string == "c");
   {
      Console.Write("You entered C");
      break;
   }
   else
   {
      Console.Write("You have not entered a valid catagory");
      Console.Write("\nPress enter to re-enter...");
      Console.ReadLine(); //If you forget this you'll never see the text in this else condition.
   }
}

Also, couldn't you use a switch-case statement for that instead of if-else? Case statements are usually more efficient.
http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx
You can use "string.ToUpper()" so you don't need to worry about whether it's upper or lower case.

I'd probably write it more like this:
Code:
While (1)
{
   Console.Clear();
   Console.Write("Please enter your catagory: ");
   string = Console.ReadLine();
   
   string = string.ToUpper;
   switch (string)
   {
    case "A": 
    case "B":
    case "C":
        Console.WriteLine("You entered {0}",string);
        goto End;
    default:
        Console.Write("You have not entered a valid catagory");
        Console.Write("\nPress enter to re-enter...");
        Console.ReadLine();
        break;
   }
}
End:
   Console.Write("Success!");
I think some versions of C# don't have fall through case statements so that might not work.
 
Last edited:
Use a while statement.
Assume "X" is your exit condition.
Code:
While (string != "X")
{
    Do something
}

This worked wonders, thanks kreij :toast:. Tried the switch streetfighter but couldnt get it to lead onto the rest of the application because of strings i was creating in the cases then trying to expand on outside of the switch, thats probably because i dont know much about switches though :o
 
Describe what you are trying to do in a little more detail.
 
I think I know what he's talking about.

The variables you want to work with outside of the switch/while must be declared outside of the switch/while. (I believe this concept is referred to as the "scope" of a "local variable"). For example:
Code:
string string = null;
While (1)
{
   Console.Clear();
   Console.Write("Please enter your catagory: ");
   string = Console.ReadLine();
   
   string = string.ToUpper;
   switch (string)
   {
    case "A": 
    case "B":
    case "C":
        Console.WriteLine("You entered {0}",string);
        goto End;
    default:
        Console.Write("You have not entered a valid catagory");
        Console.Write("\nPress enter to re-enter...");
        Console.ReadLine();
        break;
   }
}
End:
   Console.WriteLine("I HAS YER STRNG: {0}",string);
Notice how the first line of the code declares the string (initialized to 'null') which makes it available outside of the while loop and switch statement?

Hope that helps with any future C# coding you do. :)
 
@Seany : Quit tip ... don't use a goto. Ever.

The battle between people who use goto's and those who do not, has been raging for years.
It's a lot like the apple/PC or Nvidia/ATI battles.

Choose your side now ... and choose wisely.
 
I only use goto statement in batch files (because there really is no alternative). In the above example, I would have done this:
Code:
char key;
bool exit = false;
while (true)
{
   Console.Clear();
   Console.Write("Please enter your catagory: ");
   key = Console.ReadKey();
   Console.WriteLine();
   switch (key)
   {
    case 'a': 
    case 'b':
    case 'c':
        Console.WriteLine("You entered " + key.ToString());
        exit = true;
        break;
    default:
        Console.WriteLine("You have not entered a valid catagory");
        Console.Write("Press enter to re-enter...");
        key = Console.ReadKey();
        break;
   }
   if (exit)
       break;
}
Console.WriteLine()
 
Yeah, I would have assigned an exit bool as well but I can't even remember the computational issues (branch prediction) of goto statements in C#. It seemed to me that the "goto" was just simpler and given that the script itself is about as simple as it gets I assumed it was trivial.

The other option to avoid having to make a flag variable is to make a function with while/switch statement and then have "return;" instead of "goto" or "break;" inside the case statement. I'm not sure if the overhead on functions in C# makes this method worthwhile though...

Also, I'm pretty damned certain I'm over-analyzing this...
 
No real reason to use ..
Code:
if (exit) break;

since you can just use the exit boolean as the while condition ...
Code:
while (!exit)
{
    ... one of the cases sets exit to true;
}

But that's the beauty of coding. Many ways to do the same thing.

Street said:
Also, I'm pretty damned certain I'm over-analyzing this...
We're coders, it's in our nature. :D
 
The way I wrote it is more versatile because you can stop the loop before it reaches the conditional (like if there was more code under the if statement). Since I've had to do that some times, I always do it the same way.

Another advantage to not using goto is that you can make sure all streams are closed before exiting the loop (assuming the string is defined and opened inside).
 
Back
Top