| CSC300: Some common errors and advice [12/12] | ![]() ![]() |
A common problem is using < when you mean >.
In the bound of a loop this can cause big trouble!
For example, consider:
01 |
LOOP1: int i = 1; while (i > a.length) { i += 1; } |
and
01 |
LOOP2: int i = 1; while (i < a.length) { i += 1; } |
If a.length is 0 or 1, then the LOOP1 runs forever!
Another common issue that comes up is incrementing in the wrong place.
01 |
LOOP3: int i = 1; while (i < a.length) { if (a[i] == 5.0) { result += 1; i += 1; } } |
If a is length 2 or more, and a[1] != 5.0, then this is an infinite loop!
Sometimes your indentation can get messed up if you are typing for a while... To fix that, use Source > Format. That is, use the Format option on the Source menubar item.
A final common issue I will mention for now. Sometimes you may forget to put in the curly braces. This can be confusing!
01 |
LOOP4: int i = 1; while (i < a.length) if (a[i] == 5.0) { result += 1; } i += 1; |
LOOP4 looks okay, right?
But if you format, it will turn into this:
01 |
LOOP5: int i = 1; while (i < a.length) if (a[i] == 5.0) { result += 1; } i += 1; |
LOOP5 is the same as LOOP4, but the indentation has changed. It makes it clear that i is being incremented outside the loop. To fix this, you need to add curly braces:
01 |
LOOP6: int i = 1; while (i < a.length) { if (a[i] == 5.0) { result += 1; } i += 1; } |
Hurrah! finally a correct loop!