Finding Area Of Triangle In Java - java

public class RightTriangle
{
private double leg_1;
private double leg_2;
public RightTriangle ()
{
leg_1 = 1;
leg_2 = 1;
}
public RightTriangle (double s1, double s2)
{
leg_1= s1 ;
leg_2= s2 ;
}
public double findArea ()
{
double area= ((leg_1+leg_2)/2);
return area;
}
public double findPerimeter ()
{
double s3Squared= Math.pow(leg_1,2) + Math.pow( leg_2,2);
double s3= Math.sqrt(s3Squared);
double perimeter=(leg_1 + leg_2 + s3);
return perimeter;
}
public void dilate (double factor)
{
}
RightTriangle t1 = new RightTriangle (3, 4);
t1.findArea();
}
For my Java program, the constructor should construct a triangle by default with two legs with a length of one. The other constructor allows you to choose the length of the triangles two legs.
I'm trying to test my program's methods by running the "findArea" method with my t1 triangle object, however when I try to run the program I get a "identifier expeced after the token error with my my t1.findArea() code highlighted. Please help me fix this error.

You need to create a main class to get your program started. Also, this line:
t1.findArea();
needs to be placed inside a method. I propose you change the last two lines of code to this:
public static void main(String[] args) {
RightTriangle t1 = new RightTriangle (3, 4);
t1.findArea();
}

You have to add a main method to make your class runnable.
public static void main(String args[]) {
RightTriangle t1 = new RightTriangle(3, 4);
System.out.println(t1.findArea());
}
So the full code will be
public class RightTriangle {
private double leg_1;
private double leg_2;
public RightTriangle() {
leg_1 = 1;
leg_2 = 1;
}
public RightTriangle(double s1, double s2) {
leg_1 = s1;
leg_2 = s2;
}
public double findArea() {
double area = ((leg_1 + leg_2) / 2);
return area;
}
public double findPerimeter() {
double s3Squared = Math.pow(leg_1, 2) + Math.pow(leg_2, 2);
double s3 = Math.sqrt(s3Squared);
double perimeter = (leg_1 + leg_2 + s3);
return perimeter;
}
public void dilate(double factor) {
}
public static void main(String args[]) {
RightTriangle t1 = new RightTriangle(3, 4);
System.out.println(t1.findArea());
}
}

RightTriangle t1 = new RightTriangle (3, 4);
t1.findArea();
That needs to be in a method called through main
public static void main(String[] args)
{
RightTriangle t1 = new RightTriangle (3, 4);
t1.findArea();
}

Related

How do I compare 2 objects with 1 parameter?

I made a java program that compares the distance between 2 objects
I managed to figure out how to solve it when I make a class with 2 parameters and compare these with the formula seen below;
public class RasterServices {
public static double distance (SimpleRasterElement a, SimpleRasterElement b) {
double d;
d = Math.sqrt(((b.x-a.x)*(b.x-a.x)) + ((b.y-a.y)*(b.y-a.y)));
return d;
}
public class SimpleRasterElement {
public int id;
public double x;
public double y;
public double height;
}
public class SimpleRasterElementTest {
public static void main (String[] args)
{
SimpleRasterElement a, b ; // Deklarera variabeln
a = new SimpleRasterElement (); // Skapa en instans (med ’new’),
b = new SimpleRasterElement ();
// Tilldela variablerna i ’a’ värden:
a.id = 1;
a.x = 6.0;
a.y = 8.0;
a.height = 10.5;
// Tilldela variablerna i ’b’ värden:
b.id = 1;
b.x = 9.0;
b.y = 12.0;
b.height = 15.5;
System.out.println (RasterServices.distance(a,b));
}
}
I can then test this via using my test program RasterServices.distance(a,b)
But now I want to make my variables private, use getters and create the distance() method within the RasterElement-class, and now I'm hardstuck.
public class RasterElementTest {
public static void main(String[] args) {
RasterElement re_a = new RasterElement(1, 6.0, 8.0, 10.5);
RasterElement re_b = new RasterElement(1, 9.0, 12.0, 15.5);
double d = re_a.distance(re_b);
System.out.println(d);
}
}
asd
public class RasterElement {
private final int id;
private final double x;
private final double y;
private final double height;
public RasterElement (int id_nr, double x_val, double y_val, double height_val) {
id = id_nr;
x = x_val;
y = y_val;
height = height_val;
}
public int getId () {
return id;
}
public double getX () {
return x;
}
public double getY () {
return y;
}
public double getHeight () {
return height;
}
public double distance (RasterElement a) {
double d;
d = Math.sqrt(((b.getX()-a.getX())*(b.getX()-a.getX())) + ((b.getY()-a.getY())*b.getY()-a.getY()));
return d;
}
}
But here in distance() i'm only allowed ONE parameter, can someone please explain to me how I can compare two elements/objects when I'm only allowed one parameter in the function?
(By using re_a.distance(re_b); in my test-code)
Thanks, sorry for the long post B-)
(how do I get the b-value into the equation in the method distance in the class RasterElement..?)
Change b to this. Also, you can eliminate d and return directly. Like,
public double distance (RasterElement a) {
return Math.sqrt(((this.getX()-a.getX())*(this.getX()-a.getX()))
+ ((this.getY()-a.getY())*this.getY()-a.getY()));
}

Java - Static Variables

If I wanna create a static variable inside this class, which should save the total amount of all accounts. Is this right the way I did it?
Just put a code inside the constructor and good is.
Should anyway only be inside a constructor, right?
How can I print static variables so I am able to check it?
public class Account {
private static double totalBalance = 0;
private final double INTEREST_RATE = 0.015;
private int acctNumber;
private double balance;
private String name;
public Account(String name, int acctNumber, double initialBalance) {
this.name = name;
this.acctNumber = acctNumber;
this.balance = initialBalance;
this.totalBalance += this.balance;
}
public Account(String name, int acctNumber) {
this.name = name;
this.acctNumber = acctNumber;
this.balance = 0.0;
this.totalBalance += this.balance;
}
To much code for simple question. The main thing is keyword static when declaring the field in the class. Always remember that these fields are shared among all instances of the class. In other words, when some instance change the value of the static field it is reflected in the all other instances of that class. Here the simple code is better than the words:
class A {
public static int x;
}
public class Helper {
public static void main(String[] args) {
A someA = new A();
A.x = 0;
A someOtherA = new A();
A.x = 5;
//uncomment next line and see what happens
//someA.x = -55;
System.out.println("x in someA = " + someA.x);
System.out.println("x in someOtherA = " + someOtherA.x);
System.out.println("x in all instances of A = " + A.x);
}
}
EDIT:
About the question can I put the static variable inside the constructor, try this:
class B{
private static int x;
public B(int x){
B.x = x;
}
public int getX() {
return x;
}
}
public class Helper {
public static void main(String[] args) {
B bOne = new B(44);
System.out.println(bOne.getX());
B bTwo = new B(88);
System.out.println(bTwo.getX());
System.out.println(bOne.getX());
}
}
EDIT two
Here is the sample code regarding your questions in the comments:
class Acc {
public static int noOfAccounts;
public static double totalBalance;
public Acc(double balance) {
//increase the number of accounts
Acc.noOfAccounts++;
//add the balance to totalBalance
Acc.totalBalance += balance;
}
}
public class Helper {
//test
public static void main(String[] args) {
Acc aOne = new Acc(15.4);
System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
System.out.println("Acc.totalBalance) = " + Acc.totalBalance);
Acc aTwo = new Acc(100.0);
System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
System.out.println("Acc.totalBalance) = " + Acc.totalBalance);
}
}
Solution summarized:
static variable:
private static double totalBalance;
constructor 1:
totalBalance += this.balance;
others:
totalBalance += amount;
totalBalance -= (amount + fee);
totalBalance += (this.balance * INTEREST_FEE);

How to apply a value from one method to another?

Cant set radius to count square: there're two methods, but how to force Java to count my square through radius that is random from randomNumber() ?
public class Figure {
public double randomNumber() {
return Math.random() * 11;
}
public double circleArea () {
return Math.PI*Math.pow(r,2); //how to assign a variable r in order to connect to randomNumber()??
}
public static void main(String[] args) {
Figure figure = new Figure();
System.out.println("r="+figure.randomNumber()+", s="+figure.circleArea());
}
}
Few different ways. You need to choose what works best for your scenario:
You can call the method from where required.
public double circleArea () {
return Math.PI*Math.pow(randomNumber(),2);
}
You can change the method to include a variable.
public double circleArea (double r) {
return Math.PI*Math.pow(r,2);
}
public static void main(String[] args) {
Figure figure = new Figure();
double r = figure.randomNumber();
System.out.println("r=" + r + ", s=" + figure.circleArea(r));
}
All you have to do is defining a private variable that holds the r value
public class Figure {
private double r;
public double randomNumber() {
r = Math.random() * 11;
return r;
}
public double circleArea () {
return Math.PI*Math.pow(r,2); //how to assign a variable r in order to connect to randomNumber()??
}
public static void main(String[] args) {
Figure figure = new Figure();
System.out.println("r="+figure.randomNumber()+", s="+figure.circleArea());
}

aggregation in Java and methods in main method

I have such code which works well, but I wonder why method area is not possible to put in the main method
public class Circle {
Operation op;
double pi = 3.14;
double area(int radius) {
op = new Operation();
int rsquare = op.square(radius);
return rsquare * pi;
}
public static void main(String arg[]) {
Circle c = new Circle();
double s = c.area(5);
System.out.println(s);
}
class Operation {
int square(int n) {
return n * n;
}
}
}
Example which doesn't work:
public static void main(String arg[]) {
double area ( int radius){
op = new Operation();
int rsquare = op.square(radius);
return rsquare * pi;
}
The only way to nest method implementation code inside Java methods is with anonymous classes. In your case this would look like this (code has to be nested inside a class of sorts):
public static interface Circle {
double area(int radius);
}
public static interface Operation {
int square(int n);
}
public static void main(String arg[]) {
Circle c = new Circle() {
Operation op;
double pi = 3.14;
public double area(int radius) {
op = new Operation() {
public int square(int n) {
return n * n;
}
};
int rsquare = op.square(radius);
return rsquare * pi;
}
};
double s = c.area(5);
System.out.println(s);
}
Take
double area(){...}
Outside of the main method
Java doesn't support nested methods, even if it did, there would be no point to put a nonstatic method in a static method
The closest thing would be nested classes that contain methods, declared in the method

Bluej math tester class error

again I have a computer science question. I am doing a lab for AP computer science in which we are given 2 skeleton codes and a tester class and a interface class. Our job is to make the tester run with no errors. The code I got was a triangle math code (side length, perimeter, area, that sort of thing). I made it so it would all run, but one of the tests keeps failing. I dont know why, please help me.
Here is the triangle main code:
import java.util.Scanner;
import java.lang.Math.*;
import java.lang.*;
public class Triangle implements TestableTriangle
{
private int sideA, sideB, sideC;
private double perimeter;
private double theArea;
public Triangle()
{
setSides(0,0,0);
perimeter=0;
theArea=0;
}
public Triangle(int a, int b, int c)
{
sideA=a;
sideB=b;
sideC=c;
}
public void setSides(int a, int b, int c)
{
sideA=a;
sideB=b;
sideC=c;
}
public void calcPerimeter( )
{
perimeter=(sideA+sideB+sideC);
}
public void calcArea( )
{
double s;
s=(perimeter/2);
theArea=(s*(s-a)*(s-b)*(s-c));
}
public void print( )
{
System.out.println("\n\n");
System.out.println(sideA+" "+sideB+" "+sideC+"\n");
}
public int getSideA()
{
return sideA;
}
public int getSideB()
{
return sideB;
}
public int getSideC()
{
return sideC;
}
public double getPerimeter()
{
return perimeter;
}
public double getTheArea()
{
return theArea;
}
}
Here is the lab code. This class is used to test Triangle
import java.util.Scanner;
import java.lang.Math.*;
public class Lab03a //this class is used to test Triangle
{
public static void main( String[] args )
{
Scanner keyboard = new Scanner(System.in);
//ask for user input
System.out.print("Enter side A :: ");
int a = keyboard.nextInt();
System.out.print("Enter side B :: ");
int b = keyboard.nextInt();
System.out.print("Enter side C :: ");
int c = keyboard.nextInt();
Triangle test = new Triangle(a, b, c);
test.calcPerimeter();
test.calcArea();
test.print();
//ask for user input
System.out.print("Enter side A :: ");
a = keyboard.nextInt();
System.out.print("Enter side B :: ");
b = keyboard.nextInt();
System.out.print("Enter side C :: ");
c = keyboard.nextInt();
test.setSides(a,b,c);
test.calcPerimeter();
test.calcArea();
test.print();
//add one more input section
System.out.print("Enter side A :: ");
a = keyboard.nextInt();
System.out.print("Enter side B :: ");
b = keyboard.nextInt();
System.out.print("Enter side C :: ");
c = keyboard.nextInt();
test.setSides(a,b,c);
test.calcPerimeter();
test.calcArea();
test.print();
}
}
Here is the interface code:
public interface TestableTriangle
{
public void setSides(int a, int b, int c);
public void calcPerimeter( );
public void calcArea( );
public void print( );
public int getSideA();
public int getSideB();
public int getSideC();
public double getPerimeter();
public double getTheArea();
}
Here is the tester code (and below it is the error message it shows):
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TriangleTest
{
private Triangle triangle1;
/**
* Default constructor for test class TriangleTest
*/
public TriangleTest()
{
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
#Before
public void setUp()
{
triangle1 = new Triangle(37, 38, 39);
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
#After
public void tearDown()
{
}
#Test
public void testConstructorAndSides()
{
//Triangle triangle1 = new Triangle(35, 36, 37);
assertEquals(37, triangle1.getSideA());
assertEquals(38, triangle1.getSideB());
assertEquals(39, triangle1.getSideC());
}
#Test
public void testConstructorAndPerimeter()
{
//Triangle triangle1 = new Triangle(36, 37, 38);
assertEquals(0.0, triangle1.getPerimeter(), 0.1);
triangle1.calcPerimeter();
assertEquals(114.0, triangle1.getPerimeter(), 0.1);
}
#Test
public void testSetSidesAndSides()
{
//Triangle triangle1 = new Triangle(37, 38, 39);
triangle1.setSides(10, 15, 16);
assertEquals(10, triangle1.getSideA());
assertEquals(15, triangle1.getSideB());
assertEquals(16, triangle1.getSideC());
}
#Test
public void testSetSidesAndPerimeter()
{
Triangle triangle2 = new Triangle();
triangle2.calcPerimeter();
assertEquals(0.0, triangle2.getPerimeter(), 0.1);
triangle2.setSides(38, 39, 40);
assertEquals(0.0, triangle2.getPerimeter(), 0.1);
triangle2.calcPerimeter();
assertEquals(117.0, triangle2.getPerimeter(), 0.1);
}
#Test
public void testSetSidesAndTheArea()
{
Triangle triangle2 = new Triangle();
assertEquals(0.0, triangle2.getTheArea(), 0.1);
triangle2.setSides(12, 13, 14);
triangle2.calcArea();
assertEquals(-0.0, triangle1.getTheArea(), 0.1);
triangle2.calcPerimeter();
triangle2.calcArea();
assertEquals(72.30794, triangle2.getTheArea(), 0.00001);
}
}
And the error message said something was wrong with this line:
assertEquals(72.30794, triangle2.getTheArea(), 0.00001);
for some reason it causes it to fail. I do not know why, everything else works perfectly. Any help is appreciated.
Thanks
-Keelen
You forgot to take the square root of the expression you got for the area. And it seems that you are not using the right variable names:
public void calcArea( )
{
// ensure perimeter is up-to-date!
calcPerimeter();
double s = (perimeter / 2.0);
theArea = Math.sqrt(s * (s - sideA) * (s - sideB) * (s - sideC));
}
In the code
theArea=(s*(s-a)*(s-b)*(s-c));
should be
theArea=Math.sqrt((s*(s-a)*(s-b)*(s-c)));
This is because you have ill-code while calculating area of the triangle.
It should be as follows:
public void calcArea( )
{
double s;
s=(perimeter/2);
theArea=Math.sqrt((s*(s-a)*(s-b)*(s-c)));
}
Hope this helps.

Categories

Resources