Compilation errors with loops and arrays
Objectives
- Be able to recognize and correct the most common compilation errors in loops and arrays
Common compilation errors
Let’s review the common compilation errors from last week by getting this broken code to compile%7B%0A+++++++++system.out.println(arr%5Bi%5D)%3B%0A++++++%0A+++%7D%0A%7D&mode=edit).
Missing a semicolon
In a for
loop when you are missing a semicolon, Java tells you.
Scoping rules
As we saw above, because for
loops use curly braces to indicate what is inside the loop, it’s possible to forget these, with the types of error messages we’ve already seen (that don’t give the exact line number). However, if you use good indentation, these shouldn’t be too hard to find.
A related and interesting error is when you declare variables inside the for
loop block; you’ll see they can’t be used outside of the for
loop. The solution here is to move their declaration outside of the for
loop if you want to use them later, like on lines 15 and 16. Aside: typically, we wouldn’t declare i
outside of a for loop like this because the convention in Java is that it’s meant to only be used inside the loop.
Syntax errors with arrays
Don’t forget to declare arrays properly with []
, otherwise you will get errors.
Incompatible types
A new type of error we haven’t seen yet is a type mistatch. These errors can happen in regular variables too (that aren’t arrays), when you declare the variable to hold a certain type, but then assign it something else.
You may also see this error as a warning about incompatible types (for both arrays and regular variables).
Next class
Tomorrow we’ll begin HW4 problems in lecture; you might see some of these syntax errors pop up :-)