简体   繁体   English

创建字符和对象的数组?

[英]Creating an array of Chars and objects?

I am trying to create an array that contains several different things, so that I can display a sort of maze in the command line. 我试图创建一个包含几个不同事物的数组,以便可以在命令行中显示一种迷宫。 I am trying to use '*' as the walls, and ' ' as empty spaces, but I would also like to add references to different objects, such as piles of gold, and little traps that are represented by characters like 'g' for gold, and 't' for trap. 我正在尝试使用'*'作为墙壁,并使用' '作为空白空间,但我也想添加对不同对象的引用,例如成堆的金,以及用“ g”等字符表示的小陷阱黄金,“ t”表示陷阱。

All of the objects in the maze are going to be subclasses of a MazeObject class. 迷宫中的所有对象都将成为MazeObject类的子类。 So my question is whether I make the array out of chars, and how would I put object instances into the array, or should I make it a MazeObject array, but how do I include the '*' as walls, and ' ' as spaces. 所以我的问题是我是否要使数组不使用字符,以及如何将对象实例放入数组中,还是应该将其作为MazeObject数组,但是如何将'*'作为墙,而将' '作为空格呢? 。 Or is there some way to have a MazeObject array of chars? 还是有某种方法可以使字符的MazeObject数组?

MazeObject maze[][] = new MazeObject[rows][columns]

or 要么

char maze[][] = new char[rows][columns]

or polymorphism? 或多态?

MazeObject[][] maze = new char[rows][columns]

I would define the MazeObject like the code below. 我将像下面的代码一样定义MazeObject。 Notice that char representation is really just a name or a character representation of your object. 注意, char representation实际上只是对象的名称或字符表示。 Then Object actualObj will be the physical object that you want in the maze. 然后, Object actualObj将成为您在迷宫中所需的物理对象。

public class MazeObject
{
    private char representation;
    private Object actualObj;

    public MazeObject(char r)
    {
        representation = r;
    } 

    public char getRepresentation()
    {
        return representation;
    }
}

Then you can make a list out of those by doing this: 然后,您可以通过以下操作从其中列出一个列表:

int row = 5;
int col = 5;
MazeObject [][] list = new MazeObject [row] [col]; 

How do you populate a two dimensional array? 如何填充二维数组?

Answer , but still that answer is for ints. 回答 ,但是答案仍然是整数。 You are using MazeObjects so keep that in mind. 您正在使用MazeObjects因此请记住这一点。

Solution

    MazeObject [][] list = new MazeObject [5] [5];

    list[0][0] = new MazeObject('a');

    System.out.println(list[0][0].getRepresentation());

Good luck with the rest, now you have all the tools needed to fill your 2-D array. 祝您好运,现在您拥有填补二维数组所需的所有工具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM