为了账号安全,请及时绑定邮箱和手机立即绑定

数组中玩家的位置

数组中玩家的位置

湖上湖 2023-12-13 14:26:49
为什么我的保安(“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 列。


查看完整回答
反对 回复 2023-12-13
  • 1 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信