【问题标题】:How to loop while the condition is false instead of true? C#如何在条件为假而不是真时循环? C#
【发布时间】:2018-01-26 12:38:34
【问题描述】:

我正在尝试在验证的同时将字符串转换为整数

string multiplierstr;
do {
    multiplierstr = Console.ReadLine();
} while (Int32.TryParse(multiplierstr, out multiplier));

但是,当输入是整数时它会循环,我希望它在输入是字符串时循环,同时仍然使用 TryParse 方法。有什么办法吗?

【问题讨论】:

  • while (!Int32.TryParse(multiplierstr, out multiplier));
  • 请注意上面评论中的感叹号(不是运算符)。
  • 谢谢,我已经把它放在括号外了。这个问题有点没必要。
  • @Seminix 随意删除它,因为它不太可能帮助任何未来的读者。
  • 我以This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting.的身份投票结束了这个问题

标签: c# string validation integer tryparse


【解决方案1】:

使用!运算符,参考 here

string multiplierstr;
do {
    multiplierstr = Console.ReadLine();
} while (!Int32.TryParse(multiplierstr, out multiplier));

【讨论】:

    【解决方案2】:

    要让您当前的代码运行while false 而不是while true

    string multiplierstr;
    do {
        multiplierstr = Console.ReadLine();
    } while (!Int32.TryParse(multiplierstr, out multiplier));
    

    注意“!”在while() 语句的开头。

    但是,只要 multplierstr 不是 Int32(可能不是您想要的),它就会运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-24
      • 2022-11-25
      相关资源
      最近更新 更多