gpt4 book ai didi

java - 按列将数据添加到二维数组中

转载 作者:行者123 更新时间:2023-12-02 11:45:42 26 4
gpt4 key购买 nike

我目前正在尝试用 Java 为我的数据构建一个数据表。但是,我的数据按列排列(因此对于一个列标题,例如“运行量”,我有一个包含“运行量”所有值的数组)。换句话说,我有一个包含“amount run”所有值的值数组,并且我需要将它们排列到一列而不是一行中。所以我的问题是“有没有一种方法可以初始化二维数组,以便可以逐列初始化它(因为我知道初始化二维数组的唯一方法是通过执行

对象[][]数组= { {"word1","word2"},{"word3","word4"}}

但是,这是按行而不是按列。那么,我该如何初始化它,以便“word3”和“word2”位于同一个“数组”中(因为“word1”和“word2”目前位于同一个“数组”中)。

(解决方案最好不使用循环,但如果这是唯一的方法,那也可以)

最佳答案

要以除已定义的方式之外的任何方式填充整个数组,您必须知道数组的长度。这样做时您有两种选择。您可以预设确定的数组长度和宽度,

Object[][] array = new Object[3][27];

或者您可以向应用程序用户索取一份。

 System.out.print("Please enter an array length and column length: ");
int m = input.nextInt();
int x = input.nextInt();

Object[][] array = new Object[m][x];

知道数组大小后

    // If you are initializing by user input, then

System.out.println("Enter column one: ");
for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = input.nextLine();
}
}

// Will not end until the column has finished by filled with the added user input.
// You will loop until your entire array.length is filled



// Same basic principle if you are not looking to use user input.

for (int i = 0; i < array.length; i++){
for (int j = 0; j < array[i].length; j++){
array[i][j] = someObject; // someObject meaning some predetermined value(s)
}
}

希望这有帮助!

关于java - 按列将数据添加到二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48218301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com