打开字符串会跳过所有情况
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);
此代码片段生成输出:
1
+
错误 - 无法分配起始值。
标记 3
0
为什么会发生这种情况?在输出的第二行中,程序打印出extracted[used]的值为“+”,但switch语句无法转到case“+”,而是转到default,并打印出错误,并且然后打印出“结果”的占位符值。如果重要的话,提取的是一个字符串数组。
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 "+", 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试切换
extracted[used].Trim()
,您将得到正确的开关。Try switching over
extracted[used].Trim()
and you'll get the correct switch to be hit.事实上,输出的第二行并没有显示您 extracted[used] 等于“+”,但它看起来像这样。如果 extract[used] 中存在一些看不见的空格,我一点也不会感到惊讶...
您应该调试程序以确定 extract[used] 的值,而不是相信在 WriteLine 中看到的内容。
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.
我测试了以下代码,它按预期工作。所以问题肯定出在
extracted[used]
的值上。您可以这样调用它:
将此逻辑分解为代码中其自己的函数可能是个好主意。您可以独立测试该函数,然后当从代码中的其他位置调用该函数时,您就会知道问题出在调用代码中。
I tested the following code, and it works as expected. So the problem must be with the value of
extracted[used]
.You invoke it like this:
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.