C
C#7mo ago
js

foreach loop index error

foreach (string toppings in toppingsArray)
{
if (count <= toppingsArray.Length)
{
string topping = toppingsArray[count];
_names.Add(topping);
string price = toppingsArray[count + 1];
_prices.Add(price);
count = count + 2;
}
else if (count > toppingsArray.Length)
{
break;
}
}
foreach (string toppings in toppingsArray)
{
if (count <= toppingsArray.Length)
{
string topping = toppingsArray[count];
_names.Add(topping);
string price = toppingsArray[count + 1];
_prices.Add(price);
count = count + 2;
}
else if (count > toppingsArray.Length)
{
break;
}
}
5 Replies
js
jsOP7mo ago
its saying my indexes are incorrect when setting the string topping and string price line
js
jsOP7mo ago
this is the toppingsArray in question
No description
js
jsOP7mo ago
each new line is a separate item and my count variable is declared as 0 before the loop starts
333fred
333fred7mo ago
You did <=, not < But why are you even accessing the array? Foreach just gives you each element, one at a time
js
jsOP7mo ago
changed to a while loop thanks
Want results from more Discord servers?
Add your server