【问题标题】:How to loop through string array and add each element to object array如何遍历字符串数组并将每个元素添加到对象数组
【发布时间】:2019-09-17 21:33:39
【问题描述】:

我试图循环一个名为string[] splitWords 的字符串数组。数组格式如下:

 // Write your main here
    Write("Enter a number between 1 & 10: ");
    int input = Convert.ToInt32(ReadLine());

    Random ranNumberGenerator = new Random();
    int randomNumber;
    randomNumber = ranNumberGenerator.Next(1, 11);

    if (input == randomNumber)
    {
        WriteLine("correct");
    }
    else if (input < randomNumber)
    {
        WriteLine("too low");
    }
    else
    {
        WriteLine("too high");
    }

我目前正在尝试遍历将每个元素单独拆分并将其分配给对象数组的数组。例如,需要在自己的对象数组元素等(每3个元素)。因此,对象数组中总共将有 5 个元素。目前我的代码不工作,或者给我任何错误。

 // Write your main here
        Write("Enter a number between 1 & 10: ");
        int input = Convert.ToInt32(ReadLine());

        Random ranNumberGenerator = new Random();
        int randomNumber;
        randomNumber = ranNumberGenerator.Next(1, 11);

        if (input == randomNumber)
        {
            WriteLine("correct");
        }
        else if (input < randomNumber)
        {
            WriteLine("too low");
        }
        else
        {
            WriteLine("too high");
        }

【问题讨论】:

    标签: c# arrays .net loops object


    【解决方案1】:

    您的代码已关闭,您只需删除 if

    代替:

    stationNames[stationCounter] = new Station(splitWords[i], splitWords[i + 1], splitWords[i + 2]);
    if (stationCounter % 3 == 0)
    {
        stationCounter++;
    }
    

    你只需要:

    stationNames[stationCounter] = new Station(splitWords[i], splitWords[i + 1], splitWords[i + 2]);
    stationCounter++;
    

    因为循环的每次迭代都会移动 3 个增量,因此您只需每次递增 while 计数器。

    【讨论】:

      【解决方案2】:

      使用 LINQ 将使这项任务变得非常简单:

      Station[] stationNames = splitWords
        .Select(word => word.Split(' '))
        .Select(a => new Station(a[0], a[1], a[2]))
        .ToArray();
      

      【讨论】:

      • 当我尝试添加它时这似乎不起作用?任何帮助将不胜感激
      • @nextgenben99 在什么情况下它不起作用?它会产生什么错误?
      • 它说 System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
      • @nextgenben99 - 然后你有一行没有三个项目。您的真实数据是什么样的?
      • LINQ 可能超出(可能的)家庭作业的范围(太高级)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 2020-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多