我有一个名为point的类和一个演示类。我试图比较我传入演示类的每个x,y点的y值,但我似乎无法从每个点检索y值。
public class point {
// instance variables
private int x;
private int y;
// constructor
public point(int x, int y) {
this.x = x;
this.y = y;
}
// getter and setter methods
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void equals() {
if (this.x == x && this.y == y) {
System.out.println("equals");
}
}
public int isLower() {
if (this.y > y) {
return y;
}
else {
return this.y;
}
}
public double findLength() {
return Math.sqrt((this.x - x) * (this.x - x) + (this.y - y) * (this.y - y));
}
}
演示类
import java.util.Scanner;
public class pointDemo {
public static void main(String[] args) {
System.out.println("Enter the x and y coordinates for point1:");
Scanner scan = new Scanner(System.in);
int intx = scan.nextInt();
int inty = scan.nextInt();
System.out.println("Enter the x and y coordinates for point2:");
int intx2 = scan.nextInt();
int inty2 = scan.nextInt();
System.out.println("Enter the x and y coordinates for point3:");
int intx3 = scan.nextInt();
int inty3 = scan.nextInt();
System.out.println("Enter the x and y coordinates for point4:");
int intx4 = scan.nextInt();
int inty5 = scan.nextInt();
point point1 = new point(intx, inty);
point point2 = new point(intx2, inty2);
point point3 = new point(intx3, inty3);
point point4 = new point(intx4, intx4);
System.out.println(point1.isLower());
}
}
答案 0 :(得分:2)
我认为您要做的是比较两点...然后,您必须修改isLower()
public int isLower(point p){
if(y > p.y){
return p.y;
}
else{
return y;
}
}
...
System.out.println(point1.isLower(point2));
您可以对此进行增强以在所有给定点之间进行比较,或将它们存储在数组或集合中,并返回所有给定点的最低 y 。
现在,您的isLower()
功能只是将 point1.y 与来自 point1 的 this.y 进行比较(等于 point1.y )使它毫无意义(抱歉)。
答案 1 :(得分:1)
在数据对象内部进行这种比较状态跟踪会使其比必要的更复杂。在实际系统中,这会导致维护成本增加和设计脆弱。
使Point实现可比较或实现分隔符Comparator并使用SortedSet与那些或比较器并采用最后一个元素(假设您的Comparable或Comparator是升序)是一个更加惯用和面向对象的选项。
public class AscendingPointComparator implements Comparator<point> {
int compare(point a, point b) {
return a == b ? 0 :
a == null ? -1 :
b == null ? 1 :
a.getX() > b.getX() ? 1 :
a.getX() < b.getX() ? -1 :
a.getY() > b.getY() ? 1 :
a.getY() < b.getY() ? -1 :
0;
}
}
添加主要方法:
SortedSet<point> sortedPoints = new TreeSet<point>(new AscendingPointComparator<point>());
sortedPoints.add(Arrays.asList(point1, point2, point3, point4));
// this is an identity (same reference) comparison
// if you want a value comparison
// implement boolean equals(Object o) in the point class
System.out.println(point1 == sortedPoints.last());