在代码中打印出f(i).x时,将显示正确的x值。但是,当我尝试举个例子:points.get(2).x或任何其他值时,我总是得到相同的x值。任何帮助都会很棒。
主类:
import java.util.ArrayList;
public class Main {
public static ArrayList<Point> points = new ArrayList();
public static void main(String[] args) {
for (float i = -5; i <= 5; i+=0.1) {
points.add(f(i));
}
for (int i = 0; i < points.size(); i++) {
System.out.println(points.get(i).x);
// shows always the same number: 4.95...
}
}
public static Point f(float x) {
return new Point(x, (-0.15f*((x + -2.1f) * (x + -2.1f)) + 4.3f));
}
}
积分等级:
public class Point {
public static float x;
public static float y;
public Point(float x_, float y_) {
x = x_;
y = y_;
}
}
答案 0 :(得分:1)
当您在x
类中将y
和Point
定义为静态时,这就是导致所有点都具有相同值的原因。 Please read about static variables
静态成员属于该类,而不是特定的实例, 这意味着,如果您使成员成为静态成员,则无需访问即可 对象