- Home /
Array index out of range... but it is in range?
I'm an experienced programmer, I know what index out of range is, but in this instance I just cannot see the issue? I must be having a slow day! Thanks in advance to whoever can spot the bug that I seem to be missing. Amount is currently 1.45, and the denominations are 0.01, 0.05, 0.1, 0.2, 0.5 in that order in the currency array.
//currency.Length = 6 so shouldn't be an issue
int denomination = currency.Length - 1;
while (amount > 0)
{
while (amount > currency[denomination].value)
{
amount -= currency[denomination].value;
coins.Add(currency[denomination]);
yield return null;
}
denomination--;
}
Answer by troien · Jun 18, 2019 at 12:35 PM
Your problem arises when amount is equal or lower then currency[0]
but bigger then 0. Because at that point denomination--
is still called, setting denomination to -1 and if it were not for the index out of range exception, you would end up in an infinite loop there. So instead of while (amount > 0)
I would suggest using a for loop like so:
for(int denomination = currency.Length - 1; denomination >= 0; denomination--)
{
while (amount > currency[denomination].value)
{
// etc...
}
}
Aaah thank you, that should totally have been obvious to me... slow day!
Your answer
Follow this Question
Related Questions
IndexOutOfRange error on iPhone, but not on PC/Player 0 Answers
Array index is out of range 1 Answer
IndexOutOfRangeException: Array index is out of range. 2 Answers
Find if no objects with tag exist 3 Answers
Instantiating random prefabs 1 Answer