C
C#8mo 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
jsOP8mo ago
its saying my indexes are incorrect when setting the string topping and string price line
js
jsOP8mo ago
this is the toppingsArray in question
No description
js
jsOP8mo ago
each new line is a separate item and my count variable is declared as 0 before the loop starts
333fred
333fred8mo ago
You did <=, not < But why are you even accessing the array? Foreach just gives you each element, one at a time
js
jsOP8mo ago
changed to a while loop thanks
Want results from more Discord servers?
Add your server