Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

C# Inequality Operator: Checking against multiple values

I want to check if an User Input is a specific number ( a 1 or a 9), if not I want him to reenter his input. I am trying the following code:

int playerchoice = 0;
            while ((Int32.TryParse(Console.ReadLine(), out playerchoice) == false) || (playerchoice != (1 | 9)))
            {
                Console.WriteLine("Input could not be accepted, please enter a valid number");
            };

The issue seems to be with the second part of the check: No matter if I use (playerchoice != (1 | 9)) or (playerchoice != (1 & 9)), it always either checks against the 1 or the 9, not both.

What can I do to fix this? Am I using the wrong operator?

Edit: I know I could just check against each value individually, but as I plan on eventually having a lot of options this seems quite impractical.

question from:https://stackoverflow.com/questions/65601075/c-sharp-inequality-operator-checking-against-multiple-values

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest sulotion is to check against each of the values individually, but if have a lot of numbers to check against, another sulotion is to use a HashSet. Here's a simple example:

class Program {
    private static readonly HashSet<int> nums = new HashSet<int> { 1, 9, ... };
    public static void Main(string[] args) {
        int i = int.Parse(Console.ReadLine());
        if (nums.Contains(i)) {
            // do something
        } else {
            // do something else
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...