-
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{
BufferedReader console = new BufferedReader (new InputStreamReader (System.in));
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?
-
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 :-)
-
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
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks