< Day Day Up > |
Recipe 1.12 Fixing Syntax Errors Automatically1.12.1 ProblemEclipse indicates that you've got syntax errors in your code, but you don't want to have to loop up the correct syntax in the Java documentation. 1.12.2 SolutionLet Eclipse's Quick Fix suggest solutions. When you see an error/light bulb icon in the marker bar to the left of the JDT editor, click it for solutions to the error, and select the solution you want. 1.12.3 DiscussionQuick Fix is a great tool; as far as I am concerned, if Eclipse did nothing else, it still would be a worthwhile program to use just because of its Quick Fix feature. Of all the built-in components of the JDT, Quick Fix is a real favorite among programmers because it enables you to fix syntax errors almost instantaneously. For instance, say you want the example code we've developed in the previous few recipes to also display the date and time. You might use code such as this: public class FirstApp { public static void main(String[] args) { Date date = new Date( ); stayCoolText = "Stay cool."; System.out.println(stayCoolText + " Date now is " + date.toString( )); } } You might spot a few errors here; Eclipse certainly does, as indicated by the X icons in the marker bar to the left of the editor in Figure 1-15. Figure 1-15. Using Quick FixAlthough Eclipse indicates that errors exist, it doesn't leave you in the cold. If Eclipse has a Quick Fix solution to offer, a light bulb will appear next to the X icon, also shown in Figure 1-15. Tackle the first error by letting the mouse rest over the icon in the marker bar, which brings up a tool tip indicating that the Date class can't be resolved, as shown in Figure 1-16. Figure 1-16. Getting the description of an errorTo start Quick Fix and see what the JDT suggests, click the light bulb icon. You can see those suggestions in Figure 1-17; note that Quick Fix also indicates the code it's proposing to add. Double-click the import 'java.util.Date' suggestion to import the Date class so that it can be resolved. Figure 1-17. Quick Fix suggestionsThat resolves the first problem in the code. The next problem is that the variable stayCoolText hasn't been defined before being used. You can see the Quick Fix suggestions in Figure 1-18; double-click the Create local variable 'stayCoolText' option. Figure 1-18. Fixing the errorThe third error also was there because stayCoolText hadn't been declared, so that one is fixed now as well. Here's the final, fixed code: import java.util.Date; . . . public class FirstApp { public static void main(String[] args) { Date date = new Date( ); String stayCoolText = "Stay cool."; System.out.println(stayCoolText + " Date now is " + date.toString( )); } } After fixing these problems with Quick Fix, you can run the code, as shown in Figure 1-19, with no problems. Figure 1-19. Running the fixed code |
< Day Day Up > |