為什么我的保安(“S”)與唐納德(“D”)處于相同的位置。地圖應該像這樣打印出來[D----][- - - - -][- - - - -][- - S - -][- - P - -]但它卻像這樣顯示[S----][- - - - -][- - - - -][- - - - -][- - P - -]public class Main { public static void main(String[] args) { Map m = new Map(); Player p = new Player(); Donald d = new Donald(); Security s = new Security();while(true) { m.updateMap(p.row, p.col, p.character); m.printMap(); m.updateMap(p.row, p.col, '-'); m.updateMap(d.row, d.col, d.character); m.updateMap(s.row, s.col, s.character); p.move(); } }}public class Map { char map[][]; Map() { map = new char[5][5]; for(int i = 0; i<5; i++) { for(int j = 0; j<5; j++) { map[i][j] = '-'; } } } void updateMap(int row, int col, char data) { map[row][col] = data; } //prints map on the screen. void printMap() { for(int i = 0; i<5; i++) { for (int j = 0; j<5; j++) { System.out.print(map[i][j] + " "); } System.out.println(); } }}public abstract class Position { int row; int col; char character; abstract void move();}public class Donald extends Position { //Doanld Trump's Position on the Array is [0,0] Donald() { int row = 0; int col = 0; character = 'D'; } void move() { }}正如您在這里看到的,我將安全位置設置為 [3,2],但由于某種原因,它沒有將其識別為 [3,2],并將安全位置設置為 Donald 坐的 [0,0]。public class Security extends Position { Security() { int row = 3; int col = 2; character = 'S'; } void move() { }}
1 回答

倚天杖
TA貢獻1828條經驗 獲得超3個贊
該類Security繼承了屬性row和colfrom Position,但在構造函數中,您正在執行以下操作:
Security() {
int row = 3; //you are basically creating a new variable called row
int col = 2; //which is NOT the attribute (that is this.row)
character = 'S';
}
在構造函數之后,Security對象保持s.row等于s.col0。
你應該做
Security() {
this.row = 3; //you can also do row = 3;
this.col = 2; //and the compiler will understand
this.character = 'S';
}
你在 中犯了同樣的錯誤Donald:你告訴Donald要在位置 (0,0) 但然后你告訴Security要在位置 (0,0),這就是為什么Security出現但Donald沒有出現,他被覆蓋了Security。
Player正如您所設置的,它位于第 4 行第 2 列。
添加回答
舉報
0/150
提交
取消