• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

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:
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
Use a while statement.
Assume "X" is your exit condition.
Code:
While (string != "X")
{
    Do something
}
 

streetfighter 2

New Member
Joined
Jul 26, 2010
Messages
1,655 (0.33/day)
Location
Philly
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:
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
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 :eek:
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
Describe what you are trying to do in a little more detail.
 

streetfighter 2

New Member
Joined
Jul 26, 2010
Messages
1,655 (0.33/day)
Location
Philly
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. :)
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
@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.
 

FordGT90Concept

"I go fast!1!11!1!"
Joined
Oct 13, 2008
Messages
26,259 (4.63/day)
Location
IA, USA
System Name BY-2021
Processor AMD Ryzen 7 5800X (65w eco profile)
Motherboard MSI B550 Gaming Plus
Cooling Scythe Mugen (rev 5)
Memory 2 x Kingston HyperX DDR4-3200 32 GiB
Video Card(s) AMD Radeon RX 7900 XT
Storage Samsung 980 Pro, Seagate Exos X20 TB 7200 RPM
Display(s) Nixeus NX-EDG274K (3840x2160@144 DP) + Samsung SyncMaster 906BW (1440x900@60 HDMI-DVI)
Case Coolermaster HAF 932 w/ USB 3.0 5.25" bay + USB 3.2 (A+C) 3.5" bay
Audio Device(s) Realtek ALC1150, Micca OriGen+
Power Supply Enermax Platimax 850w
Mouse Nixeus REVEL-X
Keyboard Tesoro Excalibur
Software Windows 10 Home 64-bit
Benchmark Scores Faster than the tortoise; slower than the hare.
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()
 

streetfighter 2

New Member
Joined
Jul 26, 2010
Messages
1,655 (0.33/day)
Location
Philly
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...
 

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
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
 

FordGT90Concept

"I go fast!1!11!1!"
Joined
Oct 13, 2008
Messages
26,259 (4.63/day)
Location
IA, USA
System Name BY-2021
Processor AMD Ryzen 7 5800X (65w eco profile)
Motherboard MSI B550 Gaming Plus
Cooling Scythe Mugen (rev 5)
Memory 2 x Kingston HyperX DDR4-3200 32 GiB
Video Card(s) AMD Radeon RX 7900 XT
Storage Samsung 980 Pro, Seagate Exos X20 TB 7200 RPM
Display(s) Nixeus NX-EDG274K (3840x2160@144 DP) + Samsung SyncMaster 906BW (1440x900@60 HDMI-DVI)
Case Coolermaster HAF 932 w/ USB 3.0 5.25" bay + USB 3.2 (A+C) 3.5" bay
Audio Device(s) Realtek ALC1150, Micca OriGen+
Power Supply Enermax Platimax 850w
Mouse Nixeus REVEL-X
Keyboard Tesoro Excalibur
Software Windows 10 Home 64-bit
Benchmark Scores Faster than the tortoise; slower than the hare.
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).
 
Top