使用取决于整数数据的数组列表



我有3个整数数组,例如:

int[] l1 = {1,2,3};
int[] l2 = {4,5,6};
int[] l3 = {7,8,9};

我有一个整数开关,它显示了一个介于1到3之间的数字,我想知道如何将这个数字与数组联系起来。我的意思是,如果它是2,那么选择第二个数组来使用

如果我理解正确,一种选择可能是沿着以下行使用多维数组:

int[][] array = {{1,2,3}, {4,5,6}, {7,8,9}};
int[] subArray = array[2];
System.out.println(Arrays.toString(subArray));

您可以使用2D数组来实现这一点;

import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
int choice = 2;
int[] l1 = {1,2,3};
int[] l2 = {4,5,6};
int[] l3 = {7,8,9};
int[][] toChoose = new int[3][];
toChoose[0] = l1;
toChoose[1] = l2;
toChoose[2] = l3;
System.out.println(Arrays.toString(toChoose[1]));
}
}

最新更新