Fix Code Sample
Back to the Program-A-Day homepage
ProblemIdentify the problems in the code sample below. Fix the errors so that the code works correctly.
public class MyClass { private static int numInst = 0; int a; double b; public static MyClass( double b ) { this.a = 5; this.b = b; numInst++; } public static double average( int n1, int n2, int b ) { int total; total = n1 + n2 + this.b; return (double)(total / 3); } public static int getNumInst() { return this.numInst; } public static double square( double ) { return a*a; } public static double cube( double a ) { return a*getA()*getA(); } public void setNumInst( int newSum ) { numInst = newSum; } public static void setA( int newA ) { a = newA; } public double getA() { return this.a; } } |
...By Students"I can recall seeing many of the errors here in the code I wrote during my first year in Computer Science and not having a clue
what was causing them. Something like this wiki page would have saved me a lot of time spent debuggin simple errors.
| |
---|---|---|
SolutionThe first problem with this code is the static constructor. Since this needs to access instance variables, the method must be a instance method. public MyClass( double b ) { this.a = 5; this.b = b; numInst++; } The next problem is that our average() method is referencing the instance variable b, rather than the int b passed in as a parameter. To solve this, we just need to remove the this. in front of the reference to b. total = n1 + n2 + b; The getNumInst() method has a similar problem, it tries to reference this, which is not allowed in a static method. Since numInst is a static variable, we can solve this as above, simply removing the reference to this. return numInst; The are two problems with our square() method. First, there is no identifier for the parameter passed in. Second, we are referencing an instance variable from a static method. The solution to both problems is to add a as an identifier in the parameter list. public double square( double a ) The problem with cube() is that is calls an instance method from a static method. This is not allowed. Replace the calls to getA() with one call to square(a). return a*square(a); The setNumInst() method is correct as is, we don't have to make any changes to it. Although there is no reference to this, the variable a referenced by setA() is an instance variable and cannot be called from a static method. To fix this, remove the static from the method signature. public void setA( int newA ) The getA() method works correctly and needs no changes. | ||
Code |