Download 01debuggingajavaprogram

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
DEBUGGING A JAVA PROGRAM
After you have deployed a Java program you must check that it compiles and runs correctly. A
program bug is an error in the program. Debugging is the process of finding and fixing these
errors.
Types of Program Errors
A compiler error results when the compiler doesn’t understand a program statement. Such errors
are most often the results of misspelled words, bad spacing, wrong letter case or missing
punctuation. The best way to minimize these errors is to pay close attention to detail as you type
out your programs.
Examples
doubel height;
Misspelled keyword double
double height
Missing semicolon (;)
Double height;
Wrong letter case
public class Hello World
Incorrect spacing
A run-time error is not caught by the compiler but causes the computer to abnormally halt
during the program's run.
Example
Entering input that is not a floating-point number causes this code to fail.
java.util.Scanner in = new java.util.Scanner( System.in );
System.out.print( "Enter the circle's radius: " );
double radius = in.nextDouble( );
A logic error is an error in the program's underlying logic so that the program output is incorrect.
Example
This statement incorrectly calculates the mileage on a car. There is no obvious error but the
program will output the wrong answer.
mpg = gallons / miles;
Debugging a Java Program
Page 1
Debugging Compiler Errors
If the compiler encounters an error in your program, it issues a diagnostic message (or
diagnostic). The diagnostic is a clue that an error exists, but don’t rely too much on its accuracy.
A diagnostic can cite the wrong line number; its explanation can be obscure or even totally
wrong.
Example
Here is a typical Java diagnostic:
MPG1.java:10: cannot find symbol
symbol : variable Miles
location: class MPG1
Miles = 341;
^
The first line contains:
Java file name
line number of the
offending statement
description of the error
MPG1.java:10: cannot find symbol
The second line contains:
the unexpected symbol
symbol
what kind of symbol it is
: variable Miles
The third line tells you the class in which the error appears.
The fourth line reproduces the offending Java statement and the fifth line places a caret mark (^)
beneath the offending symbol.
Debugging a Java Program
Page 2
The compiler does not produce a class file to execute unless the Java file is error free. A
compilation with no errors is called a clean compile.
Follow these steps to debug your compiler errors:
Begin
Compile
program
Any
diagnostics?
NO
Done
YES
NO
NO
Fix the
FIRST one
Fix it
Any more?
YES
YES
Does it
make sense?
The picture recommends that you fix the first error and recompile if the remaining errors don’t
make sense. This is because the remaining diagnostics may be spurious – a spurious diagnostic
identifies a correct statement as being incorrect. An avalanche of spurious diagnostics is called
error cascade.
Here’s why the compiler gives spurious diagnostics. It reads the program left to right, top to
bottom and generates a diagnostic if it encounters something unexpected. After this first error,
the compiler tries to recover by skipping the program’s text until reaching a symbol it
understands. If the skipped program text has information in it that the compiler needs to parse
subsequent statements, those statements will give diagnostics even though they are correct.
Debugging a Java Program
Page 3
Therefore, always concentrate on the first diagnostic. It is the only one that you can trust to be
authentic.
Example
The following application has been seeded with one error – the opening brace ({) at line 4 has
been removed. This single error results in 28 diagnostics issued by the compiler.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MPGx
{
public static void main( String [] args )
// declare data
double miles;
// miles driven in car
double gallons; // number of gallons used
double mpg;
// miles per gallon
// initialize data
miles = 341;
gallons = 15.5;
// calculate mpg
mpg = miles / gallons;
// output results
System.out.print ( miles + " mi. / " );
System.out.print ( gallons + " gal." );
System.out.println( " = " + mpg + " mpg" );
}
}
Debugging a Java Program
Page 4
Debugging Run-Time Errors
If your running program encounters an exception – that is, a situation that it hasn’t been
programmed to deal with – it halts and generates an error message.
Example
Here is a Java run-time error message that results from entering input of the wrong data type:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextDouble(Scanner.java:2456)
at MPG.main(MPG.java:15)
The lines tell you exactly where the exception was thrown and how it was propagated back
through the chain of method calls. For example, the last line above shows:
the method that threw it
the Java file name
the line number of the
statement
at MPG.main(MPG.java:15)
Debugging Logic Errors
A program run that moves successfully to completion is called a normal termination. Even so,
the program may not be correct if it has a logic error. Logic errors do not produce error
messages; the only way to detect them is to inspect the program’s output.
Example
Suppose a program prints:
15.5 mi. / 341.0 gal. = 22.0 mpg
Since
15.5
 0.045  22 , this output is clearly wrong.
341
You hunt down the error by comparing the program’s output to what it is supposed to output.
Debugging a Java Program
Page 5
You should know the latter from having done your problem analysis and program specification.
Also, use input data for which you know the correct answer. Grab a pencil and paper and double
check your calculations.
For the former, use a symbolic debugger to step through the program and view its internal
memory.
By comparing your worked answer to the debugger’s output, you can discover the exact
statement where the program begins to go wrong.
Exercises
1.
Use jGRASP to enter, save and compile the MPGx application (page 4). Observe the error
cascade. Is the line number cited by the first diagnostic correct?
2.
Use jGRASP to enter, save and compile the application below. What is the diagnostic?
What line number does it cite? Is the explanation accurate?
1
2
3
4
5
6
7
8
9
10
11
12
public class StudyDiagnostic
{
public static void main( String [] args )
{
double cost, qty;
java.util.Scanner in = new java.util.Scanner( System.in );
System.out.print( "Enter a quantity: " );
qty = in.nextDouble( );
cost = $15,000;
System.out.println( "Total: " + qty * cost );
}
}
Debugging a Java Program
Page 6
Use jGRASP to correct the StudyDiagnostic application of the previous problem. Compile
and run it to make sure it is correct and then complete each of the following problems.
3.
On line 5 change double to doubel. Recompile the application and observe the
diagnostic. Restore the application so that it is correct.
4.
On line 8 change qty to Qty. Recompile the application and observe the diagnostic. What
does the diagnostic cannot find symbol mean? Restore the application so that it is
correct.
5.
On line 1 change StudyDiagnostic to Study Diagnostic. Recompile the
application and observe the diagnostic. Restore the application so that it is correct.
6.
Practice debugging this program. It has approximately 10 compiler errors. Identify them all.
public class Multiplierx
{
public static void main( String [] args )
{
/ / declare data
double firstnum;
double secondnum;
double product;
// input data
java.util.Scanner in = new Scanner( System.in );
System.out.print( "Enter first number to multiply: " );
double firstnum = in.nextdouble( );
System.out.print( "Enter second number to multiply: " );
double secondnum = in.nextdouble( );
// calculate result
product = 2ndnumber * 1stnumber;
// output results
System.out.print( firstNum + " * " );
System.out.print( secondNum + " = " );
System.out.println( product );
}
}
Debugging a Java Program
Page 7
7.
Practice debugging this program. It has approximately 22 compiler errors, 1 logic error and
1 usability error. Identify them all.
import java.util.scanner;
This program finds the average of three input values.
public class Arithmeticx
{
public static void main( String [] args )
// declare variables
double number1, number2, number3;
// input data
scanner in = newscanner( );
System.out.print( "Number 1? " );
System.out.print( "Number 2? " );
System.out.print( "Number 3? " );
number 1 = in.nextDouble;
number 2 = in.nextDouble;
number 3 = in.nextDouble;
// calculate average
average = num1 + num2 + num3 / 3;
// print results
system.out.print( Number1 + ", " + Number2 + " & " + Number3 );
system.out.println( " averages to " + average );
}
Debugging a Java Program
Page 8
8.
Practice debugging this program. It has approximately 8 compiler errors, 3 logic errors, 3
usability errors and 1 readability error. Identify them all.
import java.util.Scanner;
// Convert a temperature from
Fahrenheit to Celsius.
public class FahrenheitToCelsiusx
{
public static void main( String [] args ) {
// declare data
double celsius;
double fahrenheit;
// input temperature
Scanner in = new Scanner( System.in );
double celsius = in.nextDouble( );
// calculate celsius equivalent
double celsius = 5/9 * fahrenheit - 32;
// output results
System.out.println( fahrenheit, "\U00B0F = " );
System.out.println( celcius, "u00B0C" );
}
}
Debugging a Java Program
Page 9