如何用Java创建2D字符数组?我正在研究此方法是否适合我的地图目标,尽管没有发现任何帮助,但您可以继续移动角色。我以前在C ++中已经做到了这一点(有一点帮助),尽管不知道如何在Java中做到这一点。
对于C ++版本,我从一维字符串数组开始:
"#######.#.~~~####.##.......~~~..##.~~....H....######..#######",
"#####..T.#~~~..##.H......~~~...#..T.~~.........######.###....",
"######..~~~~#######...#..~~~.........~~~.##.###..#####.###...",
"...###..~~~.######...##H.~~~.@........~~.#.####...##.H.###...",
".#####..~~.~~###C.....#..~~~.....#...~~~..###..#....##....#..",
"######....~~~.~.##....#..~~~.....#....~~~.#######C...........",
"#######.H..~.~~~~#....#..~~~.....###...~~~.##########........",
"########.H...~~~~~.....~~~......H..##....~~~.H######...T...##",
(您是@符号),然后能够使用2个嵌套的for循环将每个字符串分解为单独的字符,从而将其分解成基本上是一个2D数组,您可以在其中移动字符。
这是一个好方法吗?(我花了10个小时来尝试使用基本版本)。有更好的方法吗?稍后,我想用这样的地图创建一个非常复杂的游戏,但需要帮助。
那么,您的String是否需要2D数组?为什么不存储类似“ ABCDEFGHI”的字符串并像访问3x3 2D数组一样访问它呢?
将x,y的“坐标”映射到index。
public class Char2DDemo
{
public static int ROWS = 3;
public static int COLS = 3;
public static class Char2D
{
private StringBuilder sb = null;
private int ROWS;
private int COLS;
public Char2D(String str, int rows, int cols)
{
this.sb = new StringBuilder(str);
this.ROWS = rows;
this.COLS = cols;
}
public StringBuilder getSb()
{
return sb;
}
public int getRowCount()
{
return ROWS;
}
public int getColCount()
{
return COLS;
}
public int xy2idx(int x, int y)
{
int idx = y * getRowCount() + x;
return idx;
}
public int idx2x(int idx)
{
int x = idx % getRowCount();
return x;
}
public int idx2y(int idx)
{
int y = (idx - idx2x(idx)) / getRowCount();
return y;
}
public Character getCh(int x, int y)
{
return getSb().charAt(xy2idx(x, y));
}
public void setCh(Character ch, int x, int y)
{
getSb().setCharAt(xy2idx(x, y), ch);
}
}
public static void main(String[] args) throws java.lang.Exception
{
String test = "ABC"
+ "DEF"
+ "GHI";
Char2D c2d = new Char2D(test, 3, 3);
System.out.println("Before " + c2d.getSb());
System.out.println("at [2][2] " + c2d.getCh(2, 2));
c2d.setCh('J', 0, 0);
c2d.setCh('K', 2, 2);
c2d.setCh('M', 1, 1);
System.out.println("After " + c2d.getSb());
System.out.println("at [1][0] " + c2d.getCh(1, 0));
}
}
输出:
Before ABCDEFGHI
at [2][2] I
After JBCDMFGHK
at [1][0] B
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句