while loop not exiting when value met

房东的猫 提交于 2019-12-13 08:58:06

问题


I have a scenario where I want to check the value of a cell in an application. When the value of the cell hits 0 or -1 I'd like the test to continue. So I have:

while (!cell.Value.Equals("0") || !cell.Value.Equals("-1")) 
{
    Console.WriteLine("Value ({1})",cell_value.Value);
    Thread.Sleep(15000);
}

Unfortunately, when the cell reaches 0, it doesn't appear to 'break' out of the loop.

Output:
    Value (20)
    Value (13)
    Value (10)
    Value (9)
    Value (4)
    Value (1)
    Value (0)
    Value (0)
    Value (0)
    Value (0)

Is it best to try this with a while / do + while loop or is a for loop better?

Thanks,

J.


回答1:


|| means that at least one must be true. Therefore when you enter 0 what you get is:

  1. !cell.Value.Equals("0") - "not true" = false
  2. !cell.Value.Equals("-1") - "not false" = true

and therefore it enters. You want to be using && instead:

while (!cell.Value.Equals("0") && !cell.Value.Equals("-1")) 

Or write it like this:

// while not (equals 0 or -1)
while (!( cell.Value.Equals("0") || cell.Value.Equals("-1")))



回答2:


Your condition should probably be:

while (!cell.Value.Equals("0") && !cell.Value.Equals("-1"))

As it is currently written, at least one of the sides will be true (any string is always either NOT "0" OR NOT "-1").



来源:https://stackoverflow.com/questions/46038533/while-loop-not-exiting-when-value-met

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!