为什么我的证券('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],并将安全性放置在唐纳德坐在的[0,0]
public class Security extends Position {
Security() {
int row = 3;
int col = 2;
character = 'S';
}
void move() {
}
}
import java.util.Scanner;
public class Player extends Position{
//players position starts at [4,2] on the array
Player() {
row = 4;
col = 2;
character = 'P';
}
void move() {
Scanner scanner = new Scanner(System.in);
boolean move = false;
while(!move) {
System.out.println("up: w | down: s | left: a | right: d | quit: q");
char userInput = scanner.next().toLowerCase().charAt(0);
//moving forward
if(userInput == 'w') {
if(row>0) {
row--;
move = true;
}
}
//moving left
if(userInput == 'a') {
if(col>0) {
col--;
move=true;
}
}
//moving right
if(userInput == 'd') {
if(col<4) {
col++;
move=true;
}
}
//moving down
if(userInput == 's') {
if(row<8) {
row++;
move=true;
}
}
if(move == false) {
System.out.println("You can't move here");
}
}
}
}
答案 0 :(得分:1)
类Security
从row
继承属性col
和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.col
等于0。
你应该做
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列。