【问题标题】:C# user input int to arrayC#用户输入int到数组
【发布时间】:2014-12-24 16:17:12
【问题描述】:

我要求用户输入 5 个数字并将其存储到一个数组中,以便我可以在一个方法中发送值并从每个数组中减去 5 个数字。当我使用:

for(I=0;I<5;I++) {
int[] val = Console.ReadLine();}

它说我无法将 int[] 转换为 int。我的编程有点生疏。我也不知道如何将数组值从 main 发送到方法。

【问题讨论】:

  • 您需要先创建数组,然后再循环。在循环中,读取输入,将其转换为数字,然后通过索引设置适当的数组元素。

标签: c# arrays loops for-loop


【解决方案1】:

furkle 是正确的,它不起作用,因为 console.ReadLine 方法返回一个字符串,并且您不能将字符串分配给 int 数组。但是,提供的解决方案有点笨拙,因为它一次只能从控制台读取一个字符。最好一次接受所有输入。

这是一个简短的控制台程序,

  • 从用户那里获取一个以空格分隔的整数列表
  • 使用Split(' ').ToList();将字符串转换为字符串List;
  • 将字符串 List 转换为 int List
  • 将内容读回给您。

包括错误处理。

    static void Main(string[] args){

    var intList = new List<int>();
    string sUserInput = "";
    var sList = new List<string>();
    bool validInput = true;

    do
    {
        validInput = true;
        Console.WriteLine("input a space separated list of integers");
        sUserInput = Console.ReadLine();
        sList = sUserInput.Split(' ').ToList();

        try
        {
            foreach (var item in sList) {intList.Add(int.Parse(item));}
        }
        catch (Exception e)
        {
            validInput = false;
            Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
        }
    } while (validInput == false);

    Console.WriteLine("\r\nHere are the contents of the intList:");
    foreach (var item in intList)
    {
        Console.WriteLine(item);
    }

    Console.WriteLine("\r\npress any key to exit...");
    Console.ReadKey();
    }//end main

如果您想确保用户总共只输入 5 个整数,您可以像这样执行 DO WHILE 循环:

    do
    {
        validInput = true;
        Console.WriteLine("input a space separated list of integers");
        sUserInput = Console.ReadLine();
        sList = sUserInput.Split(' ').ToList();

        if (sList.Count > 5)
        {
            validInput = false;
            Console.WriteLine("you entered too many integers. You must enter only 5 integers. \r\n");
        }
        else
        {
            try
            {
                foreach (var item in sList) { intList.Add(int.Parse(item)); }
            }
            catch (Exception e)
            {
                validInput = false;
                Console.WriteLine("An error occurred. You may have entered the list incorrectly. Please make sure you only enter integer values separated by a space. \r\n");
            }
        }

    } while (validInput == false);

【讨论】:

    【解决方案2】:

    您将从控制台输入的字符串分配给一个 int 数组。这是错误的,原因有两个:

    1. int 数组 (int[]) 是 ints 的集合。
    2. 您从控制台获取的值不是int,需要先进行解析。

    这是一个轻微的转移,但我也不认为你应该使用数组。数组在 C# 中的功能通常比内置的 List&lt;T&gt; 少得多。 (所有的摇滚明星都加入了here)有人说根本没有理由使用数组——我不会走那么远,但我认为对于这个用例来说,将项目添加到List 比分配 5 个空间并按索引初始化值。

    无论哪种方式,您都应该使用int.TryParse(),而不是int.Parse(),因为如果您不检查用户输入是否可解析为int,您将立即收到异常。因此,从用户那里获取字符串的示例代码如下所示:

    List<int> userInts = new List<int>();
    
    for (int i = 0; i < 5; i++)
    {
        string userValue = Console.ReadLine();
        int userInt;
        if (int.TryParse(userValue, out userInt))
        {
            userInts.Add(userInt);
        }
    }
    

    如果您仍想使用该数组,或者必须使用该数组,只需将 List&lt;int&gt; userInts... 替换为 int[] userInts = new int[5];,并将 userInts.Add(userInt) 替换为 userInts[i] = userInt;

    【讨论】:

    • 实际上您的代码不会编译为您的 int.TryParse 实际上并没有 userValue 作为参数...
    【解决方案3】:

    您只需要将从控制台输入的string首先解析为int。您可以通过以下方式接受int:

    for(int i=0;i<myArray.Length;i++) {
    
      myArray[i] = int.Parse(Console.ReadLine()); //Int32.Parse(Console.ReadLine()) also works
    

    就像@Furkle 所说,最好使用TryParse(),它可以让您执行异常处理。 MSDN 对此有一个很好的tutorial

    【讨论】:

      【解决方案4】:

      你先初始化数组

      int[] val = new int[5];
      

      然后当你执行 for 循环时:

      for (int i=0; i<val.Length; i++)
      {
         val[i] = int.Parse(Console.ReadLine());
      }
      

      提示:要将数组值从 main 发送到方法,只需查看 static void main 是如何形成的:

      static void Main(string[] args)
      

      意思是 main 接受控制台参数的字符串数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 1970-01-01
        • 2016-10-22
        • 1970-01-01
        • 2014-05-16
        • 2018-06-16
        相关资源
        最近更新 更多