문제

Ok, so I have made a toString() method for this Coordinate Class, but when I try to print a Coordinate using system.out.print(), it seems to ignore my method and just use the Object.toString() method, and just returns a memory address.

Here is my code for the toString method:

package spacetable;

public class Coordinate {
private int x;
private int y;

public Coordinate(){
    x=0;
    y=0;
}
public Coordinate(int x, int y){
    this.x = x;
    this.y = y;
}

public int getX(){
    return x;
}
public int getY(){
    return y;
}

public double distTo(Coordinate xy){
    double run = xy.getX() - this.getX();
    double rise = xy.getY() - this.getX();
    double dist = sqrt(run*run + rise*rise);
    return dist;
}
public double distTo(int x, int y){
    double run = x - this.getX();
    double rise = y - this.getX();
    double dist = sqrt(run*run + rise*rise);
    return dist;
}

@Override
public String toString(){
    String Strx = Integer.toString(x);
    String Stry = Integer.toString(y);
    String result = "(" Strx + ", " + Stry + ")";
    return result;  
}

}

and my code that tries to print:

package spacetable;
public class CordinateTest {

public static void main(String[] args) {
    Coordinate place = new Coordinate(2,3);
    System.out.println(place);
}
}

And the output is: spacetable.Coordinate@e53108

why is my toString() being ignored?

도움이 되었습니까?

해결책

Your code works fine for me, take a look here

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{ 
    public static class Coordinate {
       private int x = 3;
       private int y = 5;

       @Override
       public String toString(){
          String Strx = Integer.toString(x);
          String Stry = Integer.toString(y);
          String result = "(" + Strx + ", " + Stry + ")";
          return result;
       }
   }

    public static void main (String[] args) throws java.lang.Exception
    {
        Coordinate place = new Coordinate();
        System.out.println(place);
    }
}

다른 팁

are you sure you recompiled after you added the toString method. If you are using an IDE, please check that build automatically is set. If not build the code again

Also, can you paste the import command. just want to make sure you are importing your own Coordinate class and not a class of some third party jar

public class Coordinate {
    private int x;
    private int y;
    public Coordinate(int x,int y)
    {
        this.x=x;
        this.y=y;
    }
    public String toString()
    {

        String result = "("+ x + ", " + y + ")";
        return result;

    }
    public static void main(String[] args) {
         Coordinate place = new Coordinate(2,3);
            System.out.println(place);

    }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top