Я пытаюсь написать простой код, который вычисляет расстояние manhattan между двумя роботами. Манхэттенское расстояние просто | x1-x2 | + | y1-y2 |. Я написал большую часть кода, но не знаю, как получить доступ к координатам x, y второго робота, который я создал
/**
* Project 1 -- Robot Position Calculator
*
* This program creates two Robot objects and
* calculates the distance between them.
* @author your name
* @lab section number and lab instructor name
* @date date of completion
*/
import java.util.Scanner;
/**
* The name of each robot is provided as input from the user.
* The position of each robot is assigned randomly through the constructor.
* The method distance returns the distance between this robot and the other robot.
*/
public class Robot {
/**
* The name of the Robot.
*/
String name;
/**
* The x-coordinate of the Robot location.
*/
double x;
/**
* The y-coordinate of the Robot location.
*/
double y;
/**
* Constructor to assign values for instance variables
* name assigned using the passed argument. Member variables
* x and y are assigned random real values in range [0, 1).
*
* @param name the robot name
*/
public Robot(String name) {
// TODO assign this.name
this.name = name;
// TODO assign this.x and this.y using separate calls to Math.random()
x = Math.random();
y = Math.random();
}
/*
* Returns the robot name.
*
* @returns a string containing no whitespace
*/
public String getName() {
return this.name;
}
/*
* Returns the x-coordinate of the robot location
*
* @returns a real value in range [0, 1)
*/
public double getX() {
return this.x;
}
/*
* Returns the y-coordinate of the robot location
*
* @returns a real value in range [0, 1)
*/
public double getY() {
return this.y;
}
/*
* Calculate the Manhattan distance between the robot location
* and the location specified by coordinates (x, y), i.e.:
*
* @param xCoord a real value for x-coordinate
* @param yCoord a real value for y-coordinate
* @returns a real value representing the distance
*/
public double distance(double xCoord, double yCoord) {
System.out.println(x);
System.out.println(y);
double distance = Math.abs(x - this.getX()) + Math.abs(y - this.getY());
return distance;
}
/**
* main() Method
* The main method must do the following:
* Input Name for robOne
* Input Name for robTwo
* Create the robOne object
* Create the robTwo object
* Display position of robOne
* Display position of robTwo
* Calculate the distance between both robots by calling distance function
* Display distance between the robots
*
* @param args can be ignored.
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Insert your name for the first Robot below...");
String a = in.nextLine();
Robot x = new Robot(a);
System.out.println("Insert your name for the second Robot below...");
String b = in.nextLine();
Robot y = new Robot(b);
System.out.println(x.getName() + ": (" + x.getX() + ", " + x.getY() + ")");
System.out.println(y.getName() + ": (" + y.getX() + ", " + y.getY() + ")");
// TODO Call distance(double xCoord, double yCoord) method of robOne
double d = x.distance(y.getX(), y.getY());
// TODO Print out the Manhattan distance between the robots in line 3
System.out.println(d);
// Note: be sure to adhere to the output format described below
}
}
Это исправит вашу проблему:
public double distance(double xCoord, double yCoord) {
System.out.println(x);
System.out.println(y);
double distance = Math.abs(x - xCoord) + Math.abs(y - yCoord);
return distance;
}
Раньше вы вычисляли расстояние между вашим собственным объектом, и это должно быть 0 все время.
Просто сделайте это:
public double distance(Robot other) {
return Math.abs(other.x - this.x) + Math.abs(other.y - this.y);
}
Второй робот проходит вдоль при вызове метода distance
для первого робота, как
firstRobot.distance(secondRobot);
Затем координаты x и y второго робота доступны на distance
метода как other.x
и other.y
.
Обязательно проверьте, действительно ли прошедший робот один или null
. В случае передачи null
,
firstRobot.distance(null);
ваш метод будет генерировать other.x
NullPointerException
при обращении к other.x
или other.y
.
Давайте посмотрим, что вы делаете:
public double distance(double xCoord, double yCoord) {
System.out.println(x);
System.out.println(y);
double distance = Math.abs(x - this.getX()) + Math.abs(y - this.getY());
return distance;
}
Проблема с этим кодом заключается в том, что x
и this.getX()
имеют одинаковое значение. Вы вручную получаете доступ к своей переменной экземпляра x, а также используя метод getter, который вы создали, чтобы получить то же точное значение. Из-за этого ваш метод расстояния всегда будет возвращать ноль.
То, что вы хотите сделать, это сравнить ваш текущий робот (this
) с другим роботом. Итак, измените свой метод на что-то вроде этого:
public double distance(Robot other) {
return Math.abs(this.getX() - other.getX()) + Math.abs(this.getY() - other.getY());
}
Таким образом, вы получаете доступ к переменным экземпляра X и Y вашего текущего объекта, а также к объекту, который передается вашему методу.