我是一名工科学生,忙于使用DrJava作为IDE的项目(它是我们在课程中使用的标准IDE)和普林斯顿STDLIB。
我在理解,编写和使用对象方面遇到了问题。我想问一下我写下面代码的方式有什么问题。我将在编码后给出错误行:
public class GameObject
{
// Default implementation of a game object
private double G = 6.67408e-11;
private double radiusKoeff = 0.01;
public class Planet
{
double mass;
double size;
double velocityX;
double velocityY;
double positionX;
double positionY;
public Planet(double m, double vx, double vy, double px, double py)
{
mass = m;
size = m * radiusKoeff;
velocityX = vx;
velocityY = vy;
positionX = px;
positionY = py;
}//constructor for the planet type
public double GravForce(Planet a, Planet b)
{
double distanceX, distanceY, distance;
distanceX = Math.abs(a.positionX - b.positionX);
distanceY = Math.abs(a.positionY - b.positionY);
distance = Math.sqrt((distanceX)*(distanceX) + (distanceY)*(distanceY));
double force = (G * a.mass * b.mass) / (distance*distance);
return force;
}//calculates the gravitational force between two objects
}
public static void main(String[] args)
{
String filename = args[0];
Planet first = new Planet(1.25e24, 1, 0, 0, 0);
Planet second = new Planet(1e24, 1, 0, 5, 0);
**StdOut.println(GravForce( first, second ));**
}
}
错误:对于GameObject类型,未定义GravForce(GameObject.Planet,GameObject.Planet)方法。
我尝试调用的GravForce函数抛出错误。
非常感谢任何帮助。
答案 0 :(得分:0)
像这样修改你的方法
public double GravForce(Planet b)
{
double distanceX, distanceY, distance;
distanceX = Math.abs(this.positionX - b.positionX);
distanceY = Math.abs(this.positionY - b.positionY);
distance = Math.sqrt((distanceX)*(distanceX) + (distanceY)*(distanceY));
double force = (G * this.mass * b.mass) / (distance*distance);
return force;
}//calculates the gravitational force between two objects
然后在main
public static void main(String[] args)
{
String filename = args[0];
Planet first = new Planet(1.25e24, 1, 0, 0, 0);
Planet second = new Planet(1e24, 1, 0, 5, 0);
StdOut.println(first.GravForce(second));
}