Java 在循环中每次确定一个新点(带坐标),在起点停止
在main方法中,我首先希望使用readPoint方法读取起始点(该方法在点的x和y坐标中调用两次readCoordinate) 下一步,我想每次读一个新的点。我想保持循环直到再次输入起点 我该如何进行Java 在循环中每次确定一个新点(带坐标),在起点停止,java,loops,Java,Loops,在main方法中,我首先希望使用readPoint方法读取起始点(该方法在点的x和y坐标中调用两次readCoordinate) 下一步,我想每次读一个新的点。我想保持循环直到再次输入起点 我该如何进行 package domain; public class Point { private int x; private int y; public Point(int x, int y) { setX(x); setY(y);
package domain;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
setX(x);
setY(y);
}
private void setX(int x) {
checkCoordinate(x);
this.x = x;
}
private void setY(int y) {
checkCoordinate(y);
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
private void checkCoordinate(int coordinate) {
if (coordinate < 0)
throw new IllegalArgumentException("The coordinate must be greater than or equal to 0");
}
public boolean compareWithPoint(Point point) {
if (this.x == point.x && this.y == point.y)
return true;
else
return false;
}
public double calculateDistanceToPoint(Point point) {
int x1 = point.x;
int y1 = point.y;
int x2 = this.x;
int y2 = this.y;
double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
return distance;
}
}
在不考虑存储所有输入点的情况下,您可以按照以下方式执行操作:
Point startingPoint = application.readPoint("Enter first coordinate:","Enter second coordinate: ",input);
Point nextPoint = null;
while (nextPoint == null || !startingPoint.compareWithPoint(nextPoint)) {
nextPoint = application.readPoint("Enter first coordinate:","Enter second coordinate: ",input);
// TODO: Do something with nextPoint
}
此while循环将一直运行,直到nextPoint
不再等于null
(第一次迭代后应为true),并且方法compareWithPoint
返回true
Point startingPoint = application.readPoint("Enter first coordinate:","Enter second coordinate: ",input);
Point nextPoint = null;
while (nextPoint == null || !startingPoint.compareWithPoint(nextPoint)) {
nextPoint = application.readPoint("Enter first coordinate:","Enter second coordinate: ",input);
// TODO: Do something with nextPoint
}