DevX Home Today's Headlines   Articles Archive   Tip Bank   Forums

1. Registered User
Join Date
Oct 2004
Location
Chicago
Posts
108

## Oop

I have started learing OOP, and for homework my teacher assigned a program what calculates the area of a triangle. I wrote the program using some examples that I was given, and I understand the concept, but my program does not work correctly. Can someone tell me what is wrong

import java.io.*;
class Triangle{
private double a;
private double b;
private double c;
private double s =((a+b+c)/2);
void setSides (double aSide, double bSide, double cSide){
a = aSide;
b = bSide;
c = cSide;
}
double area(){
return Math.sqrt(s*((s-a)*(s-b)*(s-c)));
}
}

========================================
========================================

class TriangleArea {
/**
* @param args the command line arguments
*/
public static void main(String[] args)throws IOException{
System.out.println("Enter sides of the triangle\n");
System.out.print("Side a: ");
double a = Double.parseDouble(console.readLine());
System.out.print("Side b: ");
double b = Double.parseDouble(console.readLine());
System.out.print("Side c: ");
double c = Double.parseDouble(console.readLine());
if(a<=0|b<=0|c<=0){
System.out.println("Invalid Triangle");
}
else{
Triangle sometriangle = new Triangle();
sometriangle.setSides(a,b,c);
System.out.println("Area of this triangle is "+sometriangle.area());
}
}
}

The program compiles and executes, but when I enter the lengths of the sides I always get -0.0 as the area. Does anyboy know what I am doing wrong?

2. Registered User
Join Date
Aug 2004
Location
On the net
Posts
38
Hey Buddy,

Everything is fine with your code. The only change you have to do is at the calculation of "s".

It must be calculated w r t the values of the sides but irrespective of that u r calculating it with the initial values and it results to 0.0

and hence your area will be 0.0

Try placing s= (a+b+c)/2 statement in the function either in setSides after the assignment statements or in the area() function before calculating the area.

Good Luck,
Narayana :-)

3. Registered User
Join Date
Nov 2004
Location
Minnesota
Posts
99
I agree. s should probably not be stored at all, since it can be derived purely from the lengths of the sides anyway.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

 FAQ Latest Articles Java .NET XML Database Enterprise
 Questions? Contact us. C++ Web Development Wireless Latest Tips Open Source

×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.