0

Im trying to loop through a string array named string[] splitWords. The array is in the following format:

 // 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");
    }

Im currently trying to loop through the array which has each element split up individually and assign it to an object array. For example, need to be in their own object array element and so on (every 3 elements). And so in total, there will be 5 elements in the object array. Currently my code is not working, or giving me any errors.

 // 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");
        }

2 Answers 2

2

Your code is close, all you need to do is remove the if block

instead of:

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

You just need:

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

Because each iteration of the loop moves 3 increments so you just need to increment the while counter each time.

Sign up to request clarification or add additional context in comments.

Comments

2

Using LINQ will make this task very easy:

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

5 Comments

This doesnt seem to work when i try to add it? Any help would be greatly appreciated
@nextgenben99 In what way it doesn't work? What errors does it generate?
It says System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'
@nextgenben99 - Then you have a line that doesn't have three items on it. What does your real data look like?
There is a possibility that LINQ is out of scope (too advanced) for a (possible) homework assignment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.