如何根据对象在直线上的位置进行比较

问题描述

|| 我正在尝试编写一个将与之进行比较的方法
// If a and b lie on the same horizontal line,//    then a < b when a is to the left of b
// Otherwise,a < b when a is below b   
我真的不知道该怎么做,通常我只是比较a> b是否返回+ ve int和-ve int如果小于或等于0。 根据您的建议我的解决方案......... 我使用了吉姆·布莱克勒,拉尔夫和彼得·劳瑞的想法,并提出了这个想法。它对不起我有点困惑,没有想到笛卡尔坐标,谢谢Aasmund Eldhuset,这是我最后的比较方法。 类词典工具比较器{     //需要对此进行重写,以便...     //如果a和b位于同一条水平线上,     //然后a
    }
    else 
        return 0;
}
}     

解决方法

你是说喜欢
class Point implements Comparable<Point> {
  double x,y;

  public int compareTo(Point b) {
      // If a and b lie on the same horizontal line,if (y == b.y)
      //    then a < b when a is to the left of b
          return x < b.x ? -1 : x > b.x ? +1 : 0;
      // Otherwise,a < b when a is below b
      return y < b.y ? -1 : y > b.y ? +1 : 0;
  }
}
    ,对于a和b可以比较的任何类型,您都需要一个class属性。一旦开始更具体地思考,这很容易。 a和b的类型是什么?     ,
if (a.y == b.y) {
  return a.x < b.x;
} else {
  return a.y < b.y;
}
    ,从文本中听起来,
a
b
是笛卡尔坐标(每个都有一个x和y值)。您是否有一个代表坐标的类?如果不是,则应做一个,并且compare方法应采用该类的两个实例,并且可以使用它们的x和y值确定它们是否在同一条水平线上,或者哪个在另一条水平线上。     ,在Java中实现compare方法的一种方法是Comparable接口 它只有一种方法
int compareTo(T o)
。此方法将此对象(在其上调用该方法的对象)与指定的对象(b)进行比较。当此对象小于,等于或大于指定的对象时,返回负整数,零或正整数。 假设对象属于伪类(因为它只是伪代码),则compare方法应如下所示。
class Pseudo implements Comparable<Pseudo> {

   @Override
   int compareTo(Pseudo b) {

     if (this and b lie on the same horizontal line) {
        if (this is to the left of b) {
           return -1;
        } else {
          return 1;
        }
      } else {
         if (this is to the below of b) {
           return -1;
         } else {
            return 1;
         }
      }
   }
}
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...