从旧的二维数组中删除空值并将非空元素放入新的二维数组中 [英] Remove null from old 2d array and put the not null elements in a new 2d array

查看:46
本文介绍了从旧的二维数组中删除空值并将非空元素放入新的二维数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从旧的二维数组中删除空元素并将其放入一个新的二维数组中,但新的二维数组正在输出所有空元素.

I am trying to remove the null elements from the old 2d array and put it in a new 2d array, but the new 2d array is outputting all null elements.

String[][] status = new String[P][M];
String[][] newStatus = new String[P][M];

for (int i = 0; i < status.length; i++) {
    for (int j = 0; j < status.length; j++) {
        if (status[i][j] != null) {
            newStatus[i][j] = status[i][j];
        }
    }
}

原始二维数组:

[[O, X, null, O, O, null, null], [null, null, O, null, null, O, O]]

我希望它看起来像这样:

I want it to look like this:

[[O, X, O, O], [O, O, O]]

输出:

[[null, null, null, null, null, null, null],
 [null, null, null, null, null, null, null]]

我对二维数组不太熟悉,所以如果有人能提供帮助,我将不胜感激.谢谢

I am not that familiar with 2d arrays, so if someone could help it would be much appreciated. Thank you

推荐答案

假设 status 已经分配了值,我会尝试这样做以正确替换值.问题是数组的大小是固定的(在这种情况下是 P 乘 M),所以除非你用某些东西替换空值,否则你不能减小 2D 数组的大小,或者让每一行/列在与前面的长度相比,将二维数组想象成一个固定的正方形网格,每个值都在一个角上.

I'd try this to get the values correctly replaced, assuming status has had values assigned. The problem is that arrays are a fixed size (in this case P by M), so unless you're replacing the null values with something, you can't decrease the size of the 2D array, or have each row/column vary in length from the previous, imagine 2D arrays as a fixed grid of squares and each value is on a corner.

String[][] status = new String[P][M];
String[][] newStatus = new String[P][M];

for (int i = 0; i < status.length; i++) {
    int y = 0;
    for (int j = 0; j < status.length; j++) {
        if (status[i][j] != null) {
            newStatus[i][j - y] = status[i][j];
        } else {
            newStatus[i][M - y - 1] = " ";
            y++;
        }
    }
}

这应该提供

[[O,X,O,O, , , ],[O, O, O, , , , ]]

这篇关于从旧的二维数组中删除空值并将非空元素放入新的二维数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆