Java Reference
In-Depth Information
Debugging: Understanding and Fixing
Syntax Errors
The previous sections of this chapter described the basic components of a Java program.
When you type a program, typos and unintentional syntax errors are likely to occur.
Therefore, when you compile a program, the compiler will identify the syntax errors. In
this section, we will show how to identify and fix syntax errors.
Consider the following Java program:
1.
DEBUGGING
2
import java.util.*;
2.
3.
public class ProgramNum1
4.
{
5.
static Scanner console = new Scanner(System.in);
6.
7.
public static void main(String[] args)
8.
{
9.
int num
10.
11.
num = 18;
12.
13.
tempNum = 2 * num;
14.
15.
System.out.println("Num = " + num + ", tempNum = " - tempNum);
16.
}
(Note that the numbers 1 to 16 on the left side are not part of the program. We have
numbered the statements for easy references.) This program contains syntax errors. When
you compile this program, the compiler produces the following errors:
ProgramNum.java:9: ';' expected
int num
^
ProgramNum.java:16: reached end of file while parsing
}
^
2 errors
The expression ProgramNum.java:9 indicates that there is error in Line 9. The remaining
error indicates that ; is expected. The next line indicates that there is amissing semicolon at the
endof the statement int num . Therefore, wemust insert ; at the endof the statement in Line 9.
Next, consider the second error:
ProgramNum.java:16: reached end of file while parsing
This error occurs in Line 16 and it specifies that the end of the file is reached. This error is
not very clear at this point. However, if you look at the source code, you will realize that
there is a missing } , which should match { at Line 4. (Note that every { must have a
matching } .)
 
Search WWH ::




Custom Search