-1 java parameters
希望我可以说我是新人,但唉,我只是非常生疏.我正在尝试制作一些简单的程序,以回到几年前我学到的基础知识.目前我有两个独立的类:实体和游戏.我已经制作了一个玩家实体对象,我想在不同的方法中访问它的x和y参数,最后也是不同的类.
我的第一直觉就是使用'player.x',但遗憾的是,它只适用于同一个类,只能使用void方法.如果我尝试在其他任何地方使用它,我会在尝试引用播放器中的任何参数的行上出现"NullPointerException"错误.关于如何引用x和y位置而不抛出该错误的任何建议,或者甚至只知道为什么它只被抛入非void方法(理想情况下我想在float方法中使用它们)将会非常赞赏.这是我的实体类:
public class Entity {
public float x; //x position
public float y; //y position
public Entity(float x, float y){
this.x = x;
this.y = y;
}
//entity methods
}
Run Code Online (Sandbox Code Playgroud)
这是我的游戏类:
public class Game{
public static Entity player;
public static float posX = 2f;
public static float posY = 2f;
public Game(){
player = new Entity(posX, posY);
}
public static float test(){
float newX = player.x - 2f; //I would get the error here for example
return newX;
}
//Game methods
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
编辑
按照建议更改了Game类,仍然得到相同的错误.
public class Game {
public Entity player;
public float posX = 2f;
public float posY = 2f;
public float y = test();
public Game() {
player = new Entity(posX, posY);
}
public float test() {
float newX = player.x - 2f; //I would get the error here for example
return newX;
}
public void print() {
System.out.println(y);
}
public static void main(String[] args) {
Game game = new Game();
game.print();
}
}
Run Code Online (Sandbox Code Playgroud)
理由很简单.您正在player构造函数中创建对象.但是在静态方法中使用它.因此,永远不会调用您的构造函数.
尝试使您的方法非静态
编辑
你可以用两种方式做到,
1:让你的test()方法非静态,一切都会像魅力一样.
public float test(){
float newX = player.x -2f;
return newX
}
Run Code Online (Sandbox Code Playgroud)
并使你的Entity player非静态.
2:在调用test()方法之前,使您的字段静态并尝试初始化它们.
public class Entity {
public static float x; //x position
public static float y; //y position
public Entity(float x, float y){
this.x = x;
this.y = y;
}
//entity methods
public static void initialize(float tx, float ty){
x = tx;
y = ty;
}
public static float test(){
float newX = Player.x - 2f;
return newX;
}
Run Code Online (Sandbox Code Playgroud)
当然,第二个不是一个很好的解决方案.但是一个解决方法.