【问题标题】:Error says that it can't transform string into int错误说它无法将字符串转换为 int
【发布时间】:2020-04-01 08:49:42
【问题描述】:
      string num;
            num = Console.ReadLine();
            Console.WriteLine(num);
            switch (num)
            {case 1:
            Console.WriteLine(one);

我正在尝试做一个 c# 项目,您可以在其中键入一个从 1 到 100 的数字,然后您会看到它的写入版本。

【问题讨论】:

  • 错误告诉你真相。字符串需要解析为数值。 int.Parse() 是你要找的机器人。

标签: c# string int switch-statement console.readline


【解决方案1】:

变量num 是一个字符串。但是您在这里尝试将其与整数进行比较:

case 1:

最快的解决方案是将其与字符串进行比较:

case "1":

或者,作为一种学习体验,您可能想尝试将num 转换为int。看看int.TryParse。一个示例可能如下所示:

string num = Console.ReadLine();
int numValue = 0;
if (!int.TryParse(num, out numValue)) {
    // The value entered was not an integer.  Perhaps show the user an error message?
}

【讨论】:

    【解决方案2】:

    您提到只想打印 1 到 100 之间的数字。 这个版本就是这样做的。

    var consoleResponse = Console.ReadLine();
    
    if (int.TryParse(consoleResponse, out int parsedValue) 
            && parsedValue >= 1 
            && parsedValue <= 100) {
        Console.WriteLine(parsedValue);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2013-07-24
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多