开发者

C#-Is there a way to get a do-while to accept OR statements?

开发者 https://www.devze.com 2023-02-06 21:24 出处:网络
I\'m teaching myself some C# and got the ide开发者_如何学Goa to build a temperature calculator. I want to use a do-while loop to ensure the user picks a valid menu choice. What I tried to do was:

I'm teaching myself some C# and got the ide开发者_如何学Goa to build a temperature calculator. I want to use a do-while loop to ensure the user picks a valid menu choice. What I tried to do was:

do
{
  //etc etc etc;
} (while menuChoice != 1||2||3);

In other words, keep doing what is inside the loop unless menuChoice is 1, 2 or 3. VS2010 Express tells me I can't do that. Is there a way to do this that way or do I have to do something else? Any suggestions on how to do this or should I use some other solution?


do { // stuff
} while (menuChoice != 1 && menuChoice != 2 && menuChoice != 3);


do {
    // etc.
} while(menuChoice != 1 &&
        menuChoice != 2 &&
        menuChoice != 3
  );

Each of the clauses of a conjunction must be an expression that evaluates to a bool. Note that != 2 is not an expression that evaluates to a bool. In fact, it's not even a legal expression. This is why you must specify menuChoice != 2.

Also, note that you should use && because the clauses. You want menuChoice to equal 1, or to equal 2, or to equal 3. Therefore you want

!(menuChoice == 1 || menuChoice == 2 || menuChoice == 3)

as the condition in the while loop. By DeMorgan's Laws, this is equivalent to

menuChoice != 1 && menuChoice != 2 && menuChoice != 3


EDIT:

How about this? this would allow you to have a non-contiguous set of numbers and is far more extensible than having a million || statements...:

int[] menuOptions = { 1, 2, 3 };

...

while(!menuOptions.Contains(menuChoice))


Or:

do {
    // etc.
} while(menuChoice > 3 || menuChoice < 1);


Just to provide yet one more solution:

using System.Collections.Generic; // for the List<T>
do
{
}
while (!(new List<Int32>(new[]{ 1, 2, 3 })).Contains(menuChoice));

And yes, this is not the best solution, it is, however, an alternative (and useful if your list of options grows).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号