【问题标题】:Java - How to Modify Arrays Separately When Using a Multidimensional Array?Java - 使用多维数组时如何单独修改数组?
【发布时间】:2017-10-22 20:32:54
【问题描述】:

我有一个由两个独立数组组成的多维数组。

      // slot1 = new int[][] { {Array1}, {Array2}}
    slot1 = new int[][] { {1, 2 ,3}, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };

我正在尝试做两件不同的事情。

  1. 我正在尝试打印数组 slot1 的内容,但每个数组之间有一个空格。例如,我希望我的输出是这样的:

1 2 3 ----- 0 0 0 0 0 0 0 0 0 0 0 0 0 0

注意:在我有破折号的地方,我实际上会添加一个空格

  1. 我想知道如何分别修改每个内部数组的值?

例如,如何更改 Array2 中索引 5 的值?并增加价值1?所以如果我打印 slot1 数组,我的值应该是这样的?

1 2 3 ----- 0 0 0 0 0 1 0 0 0 0 0 0 0 0

我已经查看了与此相关的其他问题,但是在处理两个由其他数组组成的二维数组时,我还没有找到明确的答案? ArrayList 最适合这种情况吗?

这是我的完整代码

public class Sandbox {

    static int[][] slot1;

    public static void main(String[] args) {
        Sandbox.setCache();
        Sandbox.displayCache();
    }

    public static void setCache() {
        slot1 = new int[][] { { 1, 2 ,3}, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };

    }

    public static void displayCache() {
        for (int i = 0; i < slot1.length; i++) {
            for (int j = 0; j < slot1[i].length; j++) {
                System.out.print(slot1[i][j] + " "); // How to add a space between i and j? 
            }
        }
    }
}

【问题讨论】:

  • 我对这个问题投了反对票,因为没有任何研究证据。请edit 您的问题包括您所做的研究以及准确您遇到困难的地方。如果你能做到这一点,我可能会撤回我的反对票。

标签: java arrays multidimensional-array


【解决方案1】:

我假设这是一个初学者的问题。

要在 slot1 中的两个数组之间放置空格,您可以按以下简单方式进行:

public static void displayCache() {
    for (int i = 0; i < slot1.length; i++) {
        for (int j = 0; j < slot1[i].length; j++) {
            System.out.print(slot1[i][j] + " "); 
        }
        System.out.print(" "); //Add spaces here using your preferred way
    }
}

但是,您可能不希望最后一个数组后面的空格,所以这是另一种(更好的)方式:

public static void displayCache() {
    if(slot1.length > 0) {

        for (int j = 0; j < slot1[0].length; j++)
            System.out.print(slot1[0][j] + " "); 

        for (int i = 1; i < slot1.length; i++) { //Note: now i = 1
            System.out.print(" "); //Add spaces here using your preferred way
            for (int j = 0; j < slot1[i].length; j++)
                System.out.print(slot1[i][j] + " "); 
        }

    }
}

要删除每个数组最后一个元素末尾的空格,您可以应用相同的逻辑(这是您的工作)。

要更改 slot1 中的值(以您的示例为例),您可以这样做:

slot1[1][5] = 1;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2016-07-29
    • 2020-01-10
    • 2021-11-03
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多