Reputation: 65
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");
}
Upvotes: 0
Views: 625
Reputation: 1763
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.
Upvotes: 2
Reputation: 37377
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();
Upvotes: 2