开发者

Switch on a string skips all cases

开发者 https://www.devze.com 2023-03-26 03:39 出处:网络
Console.WriteLine(used+ \"\\n\"+ extracted[used]); switch (extracted[used]) { case \"*\": result = number1 * number2; break;
            Console.WriteLine(used+ "\n"+ extracted[used]);
            switch (extracted[used])
            {
                case "*": result = number1 * number2; break;
                case "/": result = number1 / number2; break;
                case "+": result = number1 + number2; break;
                case "-": result = number1 - number2; break;
                default: Console.WriteLine("Error - Could not assign starting value."); break;
            }
            Console.WriteLine("Marker 3");
            Console.WriteLine(result);

This snippet produces the output:

1

+

Error - Could not assign starting value.

Marker 3

0

Why does this happen? In the second row of the output, the program prints out that the value of extracted[used] is "+", yet the switch statement fails to go to case "开发者_StackOverflow中文版+", instead going to default, and printing out the error, and then printing out the placeholder value for "result". If it matters, extracted is an array of strings.


Try switching over extracted[used].Trim() and you'll get the correct switch to be hit.

Console.WriteLine(used+ "\n<<<"+ extracted[used] + ">>>");
switch (extracted[used].Trim())
{
    case "*": result = number1 * number2; break;
    case "/": result = number1 / number2; break;
    case "+": result = number1 + number2; break;
    case "-": result = number1 - number2; break;
    default: Console.WriteLine("Error - Could not assign starting value."); break;
}
Console.WriteLine("Marker 3");
Console.WriteLine(result); 


In fact, the second row of the output does not show you extracted[used] is equal to "+", but that it looks like it. I would not be surprised at all if there were some unseen white spaces in extract[used]...

You should debug your program to be sure of the value of extracted[used] instead of trusting what you see in WriteLine.


I tested the following code, and it works as expected. So the problem must be with the value of extracted[used].

static int binary_op(int n1, int n2, string op)
{
  int result;
  switch (op)
  {
    case "*":
      result = n1 * n2;
      break;
    case "/":
      result = n1 / n2;
      break;
    case "+":
      result = n1 + n2;
      break;
    case "-":
      result = n1 - n2;
      break;
    default:
      throw new Exception("invalid operation");
  }
  return result;
}

You invoke it like this:

binary_op(2, 2, "+");  // => 4

It might be a good idea to break this logic out into its own function in your code. You can test that function independently, and then when it breaks when called from elsewhere in your code, you will know that the problem is in the calling code.

0

精彩评论

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

关注公众号