Java Code Ponto2D, does not display distance correctly

7
package OrientacaoObjetos;

public class Ponto2D {
    //campos publicos: nao existem restricoes p/ valores de x e y
    public double x, y;

    //constr. default: ponto definido na origem(0, 0)
    public Ponto2D() {
        x = 0; y = 0;
    }
    //constr. paramentizada: ponto definido na instanciacao
    public Ponto2D(double px, double py) {
        x = px; y = py;
    }
    //determina distancia entre instancia e cordenada dada
    public double distancia(double px, double py) {
        return Math.sqrt(Math.pow(x- px, 2) + Math.pow(y- py, 2));
    }
    //determina distancia entre instancia e cordenada dada
   public double distancia(Ponto2D p) {
       return Math.sqrt(Math.pow(x- p.x, 2) + Math.pow(y- p.y, 2));
   }
   //fornece representacao textual dos objetos
   public String toString() {
       return "Ponto2D[x=" + x + ",y=" + y + "]";
   }
}

Here I define values for px and p and the creation of a new Point2D object. I put a distance and it displays only the values px and py data in the creation of the Ponto2D constructor.

package OrientacaoObjetos;

public class UsaPonto2D {
    public static void main(String[] args) {
        Ponto2D p1 = new Ponto2D(3.3, 4.6);
        p1.distancia(55.5, 32.1);
        System.out.println(p1.toString());
    }

}

What's wrong?

    
asked by anonymous 25.07.2015 / 00:22

1 answer

5

Some things are wrong:

1 - You calculate the distance but not store it anywhere.

When calling p1.distancia(55.5, 32.1); , you execute the distancia method but simply ignore its return. Ideally you store what this function returns (return) to use later. For example:

double dist = p1.distancia(55.5, 32.1);

2 - You only print the% point of%.

When calling p1 you are only printing the contents of your point object. See the System.out.println(p1.toString()); method to see what it prints. You can add in your main class a call to print the distance, previously stored (in my example, in the toString variable):

System.out.println(p1.toString());
System.out.println("Distancia: " + dist); // Nova linha adicionada

Or, alternatively, you can print directly from a distance without having temporary and intermediate storage (ie ignoring "error" 1). For example:

System.out.println(p1.toString());
System.out.println(p1.distancia(55.5, 32.1)); // Nova linha adicionada
    
25.07.2015 / 00:31