【问题标题】:Cannot implicitly convert type 'int' to 'string' for a string array无法将字符串数组的类型“int”隐式转换为“string”
【发布时间】:2021-05-02 10:17:52
【问题描述】:

我正在尝试为我的编码课程做作业,但我对此很陌生。我的班级希望有人从用户输入中将 5 个值输入到数组中。语句必须在 while 循环中。

这是我的代码

static void Main(string[] args)
        {
            string[] numbers = new string[6];
            int i = 1;
            while (i <= 5)
            {
                Console.Write("Please enter a number here:");
                numbers[i] = Convert.ToInt32(Console.ReadLine());
                i++;
            }

        

        }
    }
}

错误发生在

numbers[i] = Convert.ToInt32(Console.ReadLine());

我正在尝试将用户输入转换为 int 值,但它不允许我这样做。有什么理由吗?请让我知道并理解我对此真的很陌生。

【问题讨论】:

  • 您已经声明了一个 strings 数组,然后您尝试将 Console.ReadLine(字符串)转换为 int 的结果放入该数组。当然 C#(一种强类型语言)不允许你这样做。将您的数组声明为 int 而不是字符串。另请考虑,如果您的用户键入的不是数字,则 Convert.ToInt32 会崩溃。您应该使用 Int32.TryParse 来转换用户输入的数字
  • 看起来你得到了same(输入5个值并转换)家庭作业? ;)
  • @MickyD 好好奇;相同的任务和相同类型的问题(错误类型)。
  • @MickyD 是的哈哈

标签: c# string integer


【解决方案1】:

您正在尝试将数据类型为字符串的输入转换为 int 数据类型。 将 numbers 数组数据类型从 string 更改为 int。

int[] numbers = new int[6];

我还会通过 Int32.TryParse 添加一个检查以查看用户的输入是否确实是一个数字。

此函数将尝试将字符串(第一个参数)转换为其 32 位有符号整数表示形式的数字,并返回一个布尔值,指示转换是否成功。

 string value = Console.ReadLine();
 int number;
 bool success = Int32.TryParse(value, out number);
 if (success)
 {
    numbers.Add(number);
 }

【讨论】:

  • 这么明显的事情,没想到哈哈。谢谢
  • 没问题@H0tline (: 你能接受我的回答吗?
【解决方案2】:

这是因为您的数组的数据类型是string 类型,并且在您的用户输入中,您尝试将其转换为int,所以您肯定会遇到异常

由于您使用 "请在此处输入一个数字:" 在您的输出中,您可以将数组的类型设置为 int

  int[] numbers = new int[6];
  int i = 1;
  while (i <= 5)
  {
      Console.Write("Please enter a number here:");
      numbers[i] = Convert.ToInt32(Console.ReadLine());
      i++;
  }

【讨论】:

  • 如果您真的想提供帮助,那么您还应该解释如何解决用户插入字母而不是数字的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 2022-08-17
  • 2013-01-17
  • 1970-01-01
相关资源
最近更新 更多