2016-02-02 5 views
-1

Это задание, поэтому большая часть конструкции прописана. У нас есть пакет с двумя классами, один Car и один City. В методе main от Город, cars были настроены, чтобы работать друг с другом в 9,0. Мы должны закодировать так, чтобы программа обнаруживала, когда автомобиль падает. Я смотрю на петлю вложенного цикла в Город и не могу понять, как заставить его работать.for loop in simple java car game

Класс автомобиля:

public class Car { 
    private int x ,y; 
    private int facing; 
    /* 
    * where 0 = north, 1 = east, 2 = south, 3 = west. 
    */ 
    private int distance; 

    public Car(int x, int y, int facing){ 
     //"this" only has to be used because 
     //the variable names are identical 
     //"this" indicates that the variable 
     //declared at the top is being referenced. 
     //the x on the right-hand side is the local 
     //variable in the method 
     this.x = x; 
     this.y = y; 
     this.facing = facing; 
    } 

    public int getX() { 
     return x; 
    } 

    public void setX(int x) { 
     this.x = x; 
    } 

    public int getY() { 
     return y; 
    } 

    public void setY(int y) { 
     this.y = y; 
    } 

    public int getFacing() { 
     return facing; 
    } 

    public void setFacing(int facing) { 
     this.facing = facing; 
    } 

    public int getDistance() { 
     return distance; 
    } 

    public void setDistance(int distance) { 
     this.distance = distance; 
    } 

    public void turnLeft() { 
     if (facing == 0) { 
      facing = 3; 
     } 
     else { 
      facing -= 1; 
     } 
    } 

    public void turnRight() { 
     if (facing == 3) { 
      facing = 0; 
     } 
     else { 
      facing += 1; 
     } 
    } 

    public void move (int distance) { 
     if (facing == 0) { 
      distance = distance + y; 
      y = distance; 
     } 
     else if (facing == 1) { 
      distance = distance + x; 
      x = distance; 
     } 
     else if (facing == 2) { 
      distance = y - distance; 
      y = distance; 
     } 
     else { 
      distance = x - distance; 
      x = distance; 
     } 
    } 
} 

Город Класс:

import java.util.*; 

public class City { 
    private List<Car> cars = new ArrayList<Car>(); 
    private int sizeX; 
    private int sizeY; 

    public City (int sizeX, int sizeY) { 
    } 

public void addCar(Car car) { 
    cars.add(car); 
    } 

    public void moveCar(Car car, int distance) { 
     for (int n = 0; n<distance; n++) { 
      car.move(1); 

      for (int i = 0; i<cars.size(); i++) { 
       Car otherCar = cars.get(i); 
       if (car != otherCar) { 
        ////this is where I'm getting stuck 
        //trying to figure out how to use this 
        //to detect when cars run into each other 
       } 
      } 
     } 
     System.out.print("Car is at "+ "" + car.getX() + ","+ car.getY() +"\n"); 
    } 

    public int getSizeX() { 
     return sizeX; 
    } 

    public void setSizeX(int sizeX) { 
     this.sizeX = sizeX; 
    } 

    public int getSizeY() { 
     return sizeY; 
    } 

    public void setSizeY(int sizeY) { 
     this.sizeY = sizeY; 
    } 

    public static void main(String[] args) { 
     City city = new City(10,10); 
     Car c1 = new Car(0,0,1); 
     Car c2 = new Car(9,9,2); 
     city.addCar(c1); 
     city.addCar(c2); 
     city.moveCar(c1,9); 
     city.moveCar(c2,9); 
    } 
} 
+2

Это как вся часть задания! Сначала попробуйте сами – Idos

+0

поиск, как сравнивать объекты равенства в java – haifzhan

+1

Автомобили пробегают друг друга, когда их положение (X и Y) равны. – MaxZoom

ответ

3

По сути, это ваша проблема:

if (car != otherCar) 

Причина этого: как car и otherCar являются объектами типа Car, поэтому == w плохо проверить только, являются ли они одним и тем же экземпляром.

Обычная вещь - переопределить equals() в Car. Кажется, что вы пытаетесь определить равенство, когда оба автомобиля находятся в одном и том же координатном местоположении, поэтому я предоставлю этот намек здесь.

Что делать в случае одного из ваших параметров, являющихся null или не типа Car, или, если это тот же экземпляр (где вы бы использование ==), я оставляю в качестве упражнения для читателя.

@Override 
public boolean equals(Object other) { 
    Car otherCar = (Car) other; 
    return otherCar.getX() == this.x && otherCar.getY() == this.y; 
} 
+2

проверка 'прочее' null или нет ... – haifzhan

+6

@haifzhan: I * сказал * это упражнение для читателя. Я хорошо знаю, что этот метод 'equals' отсутствует; Я просто не хочу, чтобы кто-то был способен к карте-бланшу, копируя его в свой код. – Makoto

+0

как для карт-бланш! – Idos