简体   繁体   English

全局Java数组设置值设置为0

[英]Global Java array setting values to 0

I've a slight problem. 我有一个小问题。 I'm taking every element in a sparse matrix and putting it into a 1d array named 'b[]'. 我将稀疏矩阵中的每个元素放入一个名为“ b []”的一维数组中。 For example: 例如:

00070
00400
02000
00050
10000

Becomes: 0007000400020000005010000 成为: 0007000400020000005010000

The code below works in that at a given point within the inner-most loop b[] has the correct value as shown below. 以下代码的工作方式是,在最内层循环b []中的给定点具有正确的值,如下所示。 My problem is that outside of the inner-most loop b[] has a value of: 我的问题是,最内层循环b []的值是:

b[] = 0000000000000000000000000

I cannot understand what I'm missing. 我无法理解我所缺少的。 It should also be noted that b[] is globally defined, and instantiated within the constructor of this class. 还应注意,b []是全局定义的,并在此类的构造函数中实例化。 The problem is that I'm trying to use this 1d array in another function, and every element within the array is set to 0. 问题是我试图在另一个函数中使用此1d数组,并且数组中的每个元素都设置为0。

public void return1dSequence() {

    // Create paired objects (Pair class).

    for (int i = 0; i < a.length; i++) {

        for(int j = 0; j < a[i].length; j++) {
            this.b[i] = a[i][j];

            // System.out.print(b[i]);
            if (this.b[i] == 0) {
                pos += 1;
            } else {
                value = this.b[i];
                ml.add(new Pair(pos, value));
                pos += 1;
            }
        }
    }
}

Thanks in advance for any replies, 预先感谢您的任何答复,

Andre. 安德烈

The first thing i want to mention is that u shouldn't declare your variables (a, b....) static. 我要说的第一件事是,您不应该将变量(a,b ....)声明为静态。 Maybe u got hit by a mean side effect after creating two instances of Sparse. 创建两个稀疏实例后,您可能会受到平均副作用的打击。 Try to define them as non static and report if it still wont work. 尝试将它们定义为非静态的,并报告是否仍然无法正常工作。

Best regards Thomas 最好的问候托马斯

Try removing this from each call to b[] if you want to access b[] as static. 如果要以静态方式访问b [],请尝试将其从每次对b []的调用中删除。

Also, are you sure you are not overwritting b[] anywhere else in the code? 另外,您确定您不会在代码的其他任何地方覆盖b []吗? This is most likely the issue because of the public static declaration. 这很可能是由于公共静态声明引起的问题。 Try making it private and removing static and see if you still have the issue. 尝试将其设置为私有并删除静态文件,看看是否仍然存在问题。

You're filling in b[i] for indexes i of your outer loop... 您正在为外循环的索引i填充b[i] ...

Each time in the inner loop, you overwrite b[i] with value a[i][j] . 每次在内循环中,您都用值a[i][j]覆盖b[i] a[i][j]

Last value of a[i] array is always zero. a[i]数组的最后一个值始终为零。

That's why your b array is zero. 这就是为什么您的b数组为零。

What you want is probably: 您想要的可能是:

int counter = 0;
for (int i = 0; i < a.length; i++) {
    for(int j = 0; j < a[i].length; j++) {
        b[counter] = a[i][j];
        counter++;
    }
}

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

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