我刚刚开始用 Java 编写自己的类和方法,所以请原谅我的一些可能过于拥挤和不必要的代码。我应该使用以下方法编写一个名为 OrderedPair 的类:reflectX、reflectY、translate、rotate90、getQuadrant、getOrigPt、dilate 和 toString。
reflectX 和 reflectY 方法是故意重载的,因为我的老师希望我们在程序中实现该技术。
我的问题是我的 rotate90 方法不起作用。例如,当我旋转点 (3,-8) 4 次(应该返回原点)时,我得到的是 (-8,-8)。此外,当我打印 toString 方法时,新点的新象限不正确。这是我的代码:
public class OrderedPair{
private double original_x;
private double original_y;
private double x_value;
private double y_value;
private int original_quadrant;
private int quadrant;
public OrderedPair (double x, double y, int q){
original_x = x;
original_y = y;
x_value = x;
y_value = y;
original_quadrant = q;
quadrant = q;
}
public void reflectX (){
y_value = -y_value;
}
public void reflectX (double value){
double reflect = value - x_value;
if (reflect > 0)
x_value += 2*reflect;
else
x_value -= 2*reflect;
}
public void reflectY (){
x_value = -x_value;
}
public void reflectY (double value){
double reflect = value - y_value;
if (reflect > 0)
y_value += 2*reflect;
else
x_value -= 2*reflect;
}
public void translate (double translateX, double translateY){
x_value += translateX;
y_value += translateY;
}
public void rotate90 (int numOfRotations){
for (int rotate = 1; rotate <= numOfRotations; rotate++){
x_value = -y_value;
y_value = x_value;
}
}
public void dilate (double dilate_value){
x_value *= dilate_value;
y_value *= dilate_value;
}
public int getQuadrant(){
if (x_value>=0)
{
if (y_value >= 0)
{
quadrant = 1;
return quadrant;
}
else
{
quadrant = 4;
return quadrant;
}
}
else
{
if (y_value >= 0)
{
quadrant = 2;
return quadrant;
}
else
{
quadrant = 3;
return quadrant;
}
}
}
public String getOrigPt(){
return "( " + original_x + ", " + original_y + ")";
}
public String toString(){
return "( " + original_x + ", " + original_y + "); " + original_quadrant + "; " + "( " + x_value + ", " + y_value + "); " + quadrant;
}
}
如果有人能提供帮助,那就太好了!
最佳答案
在rotate90
中,for
循环体的第一行
x_value = -y_value;
覆盖 x_value
,因此它在第二行中不再可用。
y_value = x_value; // x_value has already been changed
这有效地将 y_value
设置为与其相反的值。使用临时变量,这样您就不会丢失旧值。
double old_x = x_value;
x_value = -y_value;
y_value = old_x;
象限确定看起来是正确的,但它依赖于正确的 x 和 y 值。更正 rotate90
方法也应该更正 getQuadrant
方法的输出。
关于java - 我的几何程序有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36320709/