有没有一种方法可以反转Java多维数组中的特定数组? [英] Is there a way to reverse specific arrays in a multidimensional array in java?
问题描述
我知道一般如何操作和创建多维数组,但我不知道该数组具有的所有实用程序和功能.我想知道的是,如果我有一个尺寸为 [5] [4]
的2D数组,我可以在第一行按顺序排列,第二行是反向排列,第三行在其中的位置打印它吗?订购...等等.
I know how to generally manipulate and create a multidimensional array but I don't know all the utils and features that arrays have. I want to know is if I have a 2D array the size of [5][4]
, can I print it where the first line is in order, second is in reverse, and the third is in order... and so on.
例如:
[1 2 3 4] //in order
[8 7 6 5] //reverse
[9 10 11 12] //in order
[16 15 14 13] //reverse
[17 18 19 20] //in order
正如我的老师所说的定义大小为m×n的二维数组.编写一个方法来初始化数组,其编号范围为1到m×n,如下所示:第一行,从左到右初始化元素;第二行从左到右初始化元素.第二行,从右向左初始化;然后切换顺序.例如,如果m = 5;和n = 4;该数组应初始化为:"
as my teacher stated "Define a two-dimensional array of size m × n. Write a method to initialize this array with numbers from 1 to m × n in the way as below: the first row, initialize the elements from left to right; the second row, initialize from right to left; then switch order. For example, if m=5; and n = 4; the array should be initialized to:"
我不确定是否应该使用temp方法或其他某种循环方法来完成该操作.
I’m not sure if it should be done using a temp method or some other loop method.
推荐答案
您不能直接将其撤消.但是您可以循环并反转其他行:
You cannot reverse it directly. But you can have a loop and reverse the alternative rows:
void reverseArray() {
Integer[][] arr = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16},
{17, 18, 19, 20}};
for (int i = 1; i < arr.length; i += 2) {
Collections.reverse(Arrays.asList(arr[i]));
}
}
这篇关于有没有一种方法可以反转Java多维数组中的特定数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!