John was asked to write a Java code to calculate the surface area of a cone. The following code was written by him: Surface area of cone is A = pi * r * l, where l = sqrt(r^2 + h^2) class area { double area(double r, double h) { double l, a; a = 22.0 / 7 * r * l; l = Math.sqrt(r * r + h * h); return a; } } Specify the type of the error in the above program, correct and write the program to be error free.
Topic: Types of errors
Answer
Type of error: this is a LOGICAL error — the slant height l is used to work out the area a before l has been given a value, so the two statements are in the wrong order. (Java is strict about this: the compiler refuses the program outright with "variable l might not have been initialized", so in BlueJ it will not even run. Name the error as logical — the fault is the order of the statements, not the way they are written.)
Corrected program:
class area { double area(double r, double h) { double l, a; l = Math.sqrt(r * r + h * h); a = 22.0 / 7 * r * l; return a; } }
Answer this kind of question in two parts: name the error type, then write the corrected code.
Here every statement is written correctly — the syntax is fine — but they run in the wrong order: a is computed from l on the line before l is assigned. That is a logical error, and swapping the two lines fixes it.
Worth knowing why BlueJ still stops you: Java will not compile a method that reads a local variable which may not have been assigned yet, so you see "variable l might not have been initialized". Most languages would happily run this and hand back a wrong number; Java catches it. In the exam, name the error as logical and show the reordered code — that is what the marking scheme wants — but if a teacher asks why it will not compile, this is the reason.