-1

I am creating a program that will outprint the coordinates of a location. When it prints it out to the file, it looks like this:

Car id   distance #spots

java.awt.Point[x=1,y=1]
java.awt.Point[x=2,y=0]

java.awt.Point[x=1,y=0]

car0 java.awt.Point[x=0,y=0] java.awt.Point[x=1,y=0] 1

car1 java.awt.Point[x=2,y=0] java.awt.Point[x=2,y=0] 2

I am trying to get rid of the java.awt.Point from showing up so it only shows the coordinates.

Heres my code: public void saveGrid(File name) throws FileNotFoundException {

    ArrayList<Car> cars = getCars();
    ArrayList<ParkingSpot> spots = getSpots();

    PrintWriter fileWriter;
    try {
        fileWriter = new PrintWriter(name);


        fileWriter.println("hi");

        fileWriter.println("\n\nCar id   distance #spots\n");
        fileWriter.println(getPartyLocation());


        for(ParkingSpot spot: spots){
            fileWriter.println(spot.getLocation());
            fileWriter.println("");
        }
        for (Car car: cars) {
            fileWriter.println(car.getId() + " " + car.getStart() + " " + car.getLocation() + " " + car.getNumSpotsTried());
            fileWriter.println("");

        }



        fileWriter.close();
    } catch (FileNotFoundException e) {
        System.err.println("FileWriting error:" + e);
        e.printStackTrace();
    }
Chris
  • 246
  • 1
  • 5
  • 15

2 Answers2

3

When you add car.getLocation() to the string, you're adding a Point object. It's implicitly converted to string with toString(). The toString method for java.awt.Point is:

public String toString() {
    return getClass().getName() + "[x=" + x + ",y=" + y + "]";
}

which is essentially:

public String toString() {
    return "java.awt.Point[x=" + x + ",y=" + y + "]";
}

Instead of relying on this default behavior, you can do the following:

// Get the car's location.
Point loc = car.getLocation();

// Create a string representation: [x,y]
String locString = "[" + loc.x + "," + loc.y + "]";

// Add the line with all the other stuff
fileWriter.println(car.getId() + " " + car.getStart() + " " + locString + " "
  + car.getNumSpotsTried());
wchargin
  • 15,589
  • 12
  • 71
  • 110
1

The java.awt.Point stuff is being printed because your gridSave method is implicitly calling java.awt.Point.toString() ... and that's what it produces. (A typical toString() is designed to produce debug output, and including the classname is appropriate in that context.)

Your possibilities are:

  • Write your own Point class with a toString() method that outputs the location in the format you want.
  • Create a subclass of java.awt.Point that overrides the toString() method.
  • Don't use the Point.toString() method. Instead, write a String formatLocation(Point) method to format a Point how you want, and use it in your gridSave method.
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216