Fix Code Sample

From CompSciWiki
Revision as of 21:11, 7 April 2010 by DonaldN (Talk | contribs)

Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Identify 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 void setNumInst( int newSum )
	{
		numInst = newSum;
	}
	
	public static void setA( int newA )
	{
		a = newA;
	}
}
 

by Students...

Solution

The 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 us 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 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 )

Code

Solution Code

Back to the Program-A-Day homepage