使用java.awt.Point正在cmd行提示符中设置,但我似乎无法初始化构造函数

时间:2013-07-02 02:56:29

标签: java point

首先,我是一名java初学者,所以如果我使用错误的词汇,请原谅我。

问题是我正在使用2个类,我似乎无法让我的构造函数保持Point x和y坐标的值。我一直在尝试不同的方式,但似乎无法得到它。任何帮助,将不胜感激。

import java.awt.Point;

公共类FindRoute {

private static boolean randomRoute = false;

/** Driver for the FindRoute project.
 * 
 * @param args an array of four integers containing [x coordinate of car, y coordinate of car, 
 * x coordinate of destination, ycoordinate of destination] 
 */
public static void main(String[] args) 
{
    if (args.length<5)
    {
        System.err.println( "Usage java FindRoute id Xstart Ystart Xend Yend [random]");
        System.exit(1);
    }

    String carId = args[0];
    int xCar = Integer.parseInt(args[1]);
    int yCar = Integer.parseInt(args[2]);
    int xDestination = Integer.parseInt(args[3]);
    int yDestination = Integer.parseInt(args[4]);

    Car car = new Car(new Point(xCar, yCar), carId);

    System.out.println(car);
    car.setDestination(new Point(xDestination, yDestination));
    System.out.println(car);    
    System.out.println("xcar= " + xCar);
    System.out.println("ydest = " + yDestination);

    if (args.length == 6) {
        if (args[5].startsWith("r"))
            car.setRandomRoute(true);


    }
    System.out.println(car);


}

然后是构造函数和toString

public Car (Point car, String carID) {

        this.xCar = xCar;
        this.yCar = yCar;
        this.carID= carID;
public String toString() {
        return "Car [id = " + carID + ", location = [x=" + xCar + ", y=" + yCar + "], destination = [x=" + xDestination + ", y=" + yDestination + "]]";

我的输出将拉出字符串,但将车点设置为0,0。如果这是一个不正确的提问方式,请给我提示。提前致谢

1 个答案:

答案 0 :(得分:0)

public Car (Point car, String carID) {

        this.xCar = xCar;
        this.yCar = yCar;
        this.carID= carID;
}

你的构造函数是错误的,你要为同一个引用分配相同的引用,你应该这样做

public Car (Point car, String carID) {
        this.myPoint = car;
        this.carID= carID;
}

OR

public Car (Point car, String carID) {
            this.xCar = car.x;
            this.yCar = car.y;
            this.carID= carID;
}