# how to call a method from one class to a method from another class

2

The question is this, I have to calculate the perimeter of a triangle but I need to call the method `calcularDistancia` of `class Punto` a `class Triangulo` in the method `calcularPerimetro` or in simple terms put a method inside another method .

``````import java.awt.Graphics;

public class Punto {

private int x;
private int y;

@Override
public String toString() {
return "X=" + x +"\n"
+"Y=" + y + "";
}

public Punto(int x, int y) {
super();
this.x = x;
this.y = y;
}

public int getX() {
return x;
}

public int getY() {
return y;
}
public void mostrar() {
System.out.println(this.toString());
}

public double calcularDistancia(Punto pb) {
double dis=Math.sqrt(Math.pow(x-pb.getX(),2))
+Math.pow(y-pb.getX(),2);
return dis;
}

public class Triangulo {

private Punto puntoAX,pAY;
private Punto  puntoBX,pBY;
private Punto puntoCX,pCY;

public Triangulo(int puntoAX, int pAY, int puntoBX, int pBY, int puntoC, int pCY) {
super();
this.puntoAX = new Punto(puntoAX,pAY);
this.puntoBX =new Punto(puntoBX,pBY);
this.puntoCX = new Punto(puntoC,pCY);
}

@Override
public String toString() {
+"\nPunto A\n"+
puntoAX+
"\nPunto B\n"+
puntoBX+
"\nPunto C\n"+
puntoCX
;
}

System.out.println(this.toString());
System.out.println();
}

public double calcularPerimetro() {
return 0;

}

}
``````

asked by juanito 09.05.2018 в 03:19
source

3

If I did not get it wrong, to call the function `calcularDistancia` of `Punto` from any method of the class `Triangulo` it would suffice to instantiate an object of type `Punto`

For example;

``````public double calcularPerimetro() {
Punto punto = new Punto(2,3);
double aux = punto.calcularDistancia(punto);
//Aquí ya se podrías trabajar tranquilamente con el retorno de calcularDistancia
return aux;
}
``````

I hope you find it useful, greetings

source
0

I understand that your Point class contains a method to calculate the distance to another (or the same) instance of Point, that is, the distance between a given point and any other, of this then, in the method of calculating your level. Triangle class, having already the instances of the points then you do not have to do more than add the distances between each of them, it would be something like that if I'm not wrong:

``````public double calcularPerimetro() {
return this.puntoAX.calcularDistancia(this.puntoBX)
+ this.puntoBX.calcularDistancia(this.puntoCX)
+ this.puntoCX.calcularDistancia(this.puntoAX);
}
``````