Difference between revisions of "Fix Code Sample"

From CompSciWiki
Jump to: navigation, search
Line 25: Line 25:
  
 
|SideSection=
 
|SideSection=
[[Image:OperatingSystemExample.jpg|float|267px]]
+
[[Image:wiki_method02.jpg|float]]
 
<BR>
 
<BR>
Taken from http://www.flickr.com/photos/daniello/565304023/
 
 
An image or By Students section
 
  
 
|Solution=The problem with this code is that it attempts to use instance variables in a static method.
 
|Solution=The problem with this code is that it attempts to use instance variables in a static method.

Revision as of 11:59, 6 April 2010

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 Triangle
{
   int base;
   int height;

   public static int getArea()
   {
      return ( this.base * this.height / 2 );
   }
}

public static void main()
{
   Triangle tri = new Triangle();
   int area;

   area = tri.getArea();
}
 

SideSectionTitle

float

Solution

The problem with this code is that it attempts to use instance variables in a static method. To fix it, you must pass the arguments in as parameters.

Code

Solution Code

Back to the Program-A-Day homepage