简体   繁体   English

for 循环创建对象数组会导致错误的值

[英]for-loop creating array of objects leads to wrong values

I am currently trying to create an array of objects out of a char Array.我目前正在尝试从字符数组中创建一个对象数组。 My problem is that somehow the for-loop seems to insert wrong values into the objects.我的问题是 for 循环似乎以某种方式将错误的值插入到对象中。 And I just can't figure out what's going wrong.我就是无法弄清楚出了什么问题。 I was trying to fix it for hours but nothing worked.我试图修复它几个小时,但没有任何效果。

For example: The if inside of the for loop detects it is at the right char '@' and j=6, k=5.例如:for 循环内部的 if 检测到它在正确的字符 '@' 和 j=6, k=5 处。 (checked it with System.out.println().) I tell it to create an object inside for the GameObject array and give it the appropriate coordinates (x=k, y=j). (用 System.out.println() 检查它。)我告诉它在里面为 GameObject 数组创建一个对象,并给它适当的坐标(x=k,y=j)。 But for some reason the coordinates turn out to be (k=)x=5 and (j=)y=5 instead?!但是由于某种原因,坐标变成了 (k=)x=5 和 (j=)y=5 ?!

Both values always seem to be identical for some reason.由于某种原因,这两个值似乎总是相同的。 No matter what, it's always 1,1;不管怎样,它总是 1,1; 2,2; 2,2; 3,3 etc... The number is basically k (=the intended y-coordinate) taken twice. 3,3 等等...这个数字基本上是 k(= 预期的 y 坐标)两次。 It seems to not access the "j" correctly?它似乎没有正确访问“j”?

The object array itself is all right, just the values inside of the objects turn out wrong.对象数组本身没问题,只是对象内部的值出错了。

In code, the method looks like this:在代码中,该方法如下所示:

public static GameObject[][] initGO(int x, int y) throws IOException {

    GameObject[][] goMap = new GameObject[x][y];
    LoadFile loader = new LoadFile();
    char[] ch = loader.readChar("src\\control\\bla.txt");

    int i = 0;
    while (i < ch.length) {
        for (int j = 0; j < y; j++) {
            for (int k = 0; k < x; k++) {
                if (ch[i] == '@') {
                    goMap[k][j] = new Player(k, j, "Player");
                }
                i++;
            }
        }
    }
    return goMap;
}

Player just looks like this:播放器看起来像这样:

public class Player extends GameObject {

    public Player(int x, int y, String name) {
        super(x, y, name);
        this.x=y;
        this.y=y;
        this.name = name;
    }
}

Thanks a lot for anyone trying to help!非常感谢任何试图提供帮助的人!

You made a simple copy-paste-edit error when setting variables.您在设置变量时犯了一个简单的复制粘贴编辑错误。 Look at this part of the code:看这部分代码:

public Player(int x, int y, String name) {
    super(x, y, name);
    this.x=y; // <-- This should be "this.x=x;"
    this.y=y;
    this.name = name;
}

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

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