2つのクラスを作成しようとしています.1つはポイントを定義し、もう1つは配列操作用です。私はy座標に基づいて昇順で座標の配列をソートするメソッドを作成しようとしています。私は以下の例を試してみましたが、配列が部分的にしかソートされていないランタイムエラーが発生しています。配列の並べ替えが遅すぎる
public class Point
{
private double x;
private double y;
public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
public boolean lessThan(Point anotherPoint)
{
if(y < anotherPoint.y)
{
if(x < anotherPoint.x)
{
return true;
}
}
return false;
}
}
public class PointArray
{
private Point[] points = new Point[count];
public PointArray(double[] doubleArray)
{
if(doubleArray.length % 2 == 0)
{
for(int i = 0, j = 0; i < 3; i++, j += 2)
{
double x = doubleArray[j];
double y = doubleArray[j + 1];
points[i] = new Point(x, y);
}
}
else
{
System.out.println("Error: The given array must be even.");
System.exit(0);
}
}
public void sort()
{
double x = 0;
double y = 0;
Point newPoint = new Point(x, y);
Point temp = new Point(x, y);
for (int i = 0; i < points.length - 1; i++)
{
for(int j = i + 1; j < points.length; j++)
{
int minIndex = i;
if(points[minIndex].lessThan(points[j]) == false)
{
temp = points[minIndex];
points[minIndex] = points[j];
points[j] = temp;
}
}
}
}
このコードは、配列{5.6, 7.1, 4.9, 13.17, 9.3, 2.9}
が最初順序対{(5.6, 7.1), (4.9, 13.17), (9.3, 2.9)}
として記憶させます。正しくソートすることはありません。第1および第3の点が交換された後、第3および第3の点のy座標がより小さくても、第2および第3の点は交換されない。
[(9.3, 2.9), (4.9, 13.17), (5.6, 7.1)]
EDIT:同じ割り当てに関連するもう1つの問題が発生しました。このメソッドは、2つのPointArrayオブジェクトを使用して、xおよびyコンポーネントによって等しいかどうかを比較します。私の考えは、両方の配列を並べ替え、Pointクラスのメソッドを使用してコンポーネントを比較することでしたが、どのPoint X座標を(x、y)点で定義するかはわかりません。
public boolean equals(Point anotherPoint)
{
if(x == anotherPoint.x && y == anotherPoint.y)
{
return true;
}
return false;
}
public boolean equals(PointArray anotherPointArray)
{
double x = 0;
double y = 0;
double xAnother = 0;
double yAnother = 0;
Point newPoint = new Point(x, y);
Point newAnotherPoint = new Point(xAnother, yAnother);
anotherPointArray.sort();
for(int i = 0; i < points.length; i++)
{
for(int j = 0; i < points.length; j++)
{
if(newPoint.equals(newAnotherPoint))
{
return true;
}
}
}
return false;
}
簡単な方法は、あなたの 'Point'クラスに' Comparable'インターフェースを実装し、 'compareTo(Object o)'メソッドをオーバーライドして比較ロジックを定義することです。あなたはそれを許可されていますか? –
私たちはそれについてまだ学んでいません。 –
あなたの問題の声明は正確に何ですか? –