[英]Trying to one class constructor to use some of the parameters from another class constructor
[英]Java - trying to initialise an object with parameters passed in another constructor, in another class?
目前非常基本的java知識,在嘗試創建Pacman游戲時需要一些幫助。
目前我有三個類,玩家類,點類和游戲類,所有這些類都可以創建Pacman的基本游戲。
我遇到的問題是:
我需要'initialX和initialY字段如下所示(這些將是用戶輸入的坐標);
public class Player
{
private int x, y, collectedDots;
public Player(int initialX, int initialY)
{
x = initialX;
y = initialY;
collectedDots = 0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
在游戲類中的新“玩家”對象中作為我的參數傳遞。
public class Game
{
public Game()
{
Player player = new Player();
Dot dot1 = new Dot();
Dot dot2 = new Dot();
Dot dot3 = new Dot();
}
}
這讓我很難過,我假設我要么走錯了路,要么我完全錯過了什么。
您聲明的構造函數接受兩個int參數,並在不發送任何參數的情況下調用它。
當使用下面的行時,編譯器將查找不帶參數的默認構造函數,但它會因為你沒有聲明默認值而失敗,但你聲明了一個帶有兩個int參數的構造函數。
Player player = new Player();
有了這條線:
Player player = new Player(1, 2);// pass two int parameters t your defined constructor.
您可以在Player
類中定義變量,然后將這些變量分配給同一類的構造函數中的其他變量,如下所示:
public class Player
{
private int x, y, collectedDots;
int initialX = 15;
int initialY = 20;
public Player()
{
x = initialX;
y = initialY;
collectedDots = 0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
現在你的x
等於15, y
等於20.但是這些值都是Player
類的一部分。 但是,您在Game
類中創建了Player
類的對象,通過該對象,您可以像這樣訪問x
和y
:
public class Game
{
public Game()
{
Player player = new Player();
System.out.println(player.getX()); // prints out 15 in the console
System.out.println(player.getY()); // prints out 20 in the console
Dot dot1 = new Dot();
Dot dot2 = new Dot();
Dot dot3 = new Dot();
}
}
您當然可以使用這些值執行任何操作(例如將它們分配給Game
類中的新變量並在那里操作它們)。 我只是將它們打印出來,這樣你就可以看到它來自Player
類的值。
UPDATE
您可以在創建Player
對象之前獲取用戶輸入,然后將這些值傳遞給Player
類的構造函數,如下所示:
public class Game
{
public Game()
{
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
Player player = new Player(i,j);
System.out.println(player.getX()); // prints out 15 in the console
System.out.println(player.getY()); // prints out 20 in the console
Dot dot1 = new Dot();
Dot dot2 = new Dot();
Dot dot3 = new Dot();
}
}
當然,這是為了保持您的Player
類最初發布它的方式。 但是如果你想繼續改變x
和y
的值,你總是可以提供Setter方法。 你的課程將成為:
public class Player
{
private int x, y, collectedDots;
public Player(int initialX, int initialY)
{
x = initialX;
y = initialY;
collectedDots = 0;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
}
每當你想從Game
類改變x
和y
的值時,你只需要做以下(只是一個例子):
public class Game
{
public Game()
{
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
int j = sc.nextInt();
Player player = new Player(i,j);
player.setX(35);
player.setY(48);
}
}
再次,這只是一個例子。 我不會在構造函數中完成所有這些操作,而只是使用它來解釋如何做你想做的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.