有没有办法使用扫描仪来设置数组中的维数?

is there a way to use a Scanner to set the number of dimensions in an array?

我想做的是根据用户输入创建一个包含多个组(数组行)的列表(数组维度)。 例如:

// get list number;
Scanner input = new Scanner(System.in);
System.out.println("How many lists do you want to create?");
int listNum = input.nextInt();

// listNum = 4
// create array with 4 dimensions;

// get  list size;
for (int i=0; i<listNum; i++) {
    System.out.println("How many entries are in list No."+(i+1)+" ?");
    // TBC
}

好吧,你可以做这样的事情,但它非常讨厌。假设最大为 4

int dim = input.nextInt(); //4
Object wtfarray = getArray(dim,2);
putAvalueOnFirstJustForFun(wtfarray,dim,-99);
//throw new Exception("Please kill me");

/*wtfarray 
    
    [[[[-99, 0], [0, 0]], [[0, 0], [0, 0]]], 
     [[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]
*/


//...
void putAvalueOnFirstJustForFun(Object array, int dim, int value)
{
  switch(dim)
  {
    case 1:  {((int[])array)[0] = value; return;}
    case 2:  {((int[][])array)[0][0] = value; return;}
    case 3:  {((int[][][])array)[0][0][0] = value; return;}
    //...until your max    
    default: {((int[][][][])array)[0][0][0][0] = value;}
}

static Object getArray(int dimensions, int size)
{
  switch (dimensions)
  {
     case 1:  {return new int[size];}
     case 2:  {return new int[size][size];}
     case 3:  {return new int[size][size][size];}
     //...until your max    
     default: {return new int[size][size][size][size];}
   }
}

这东西很丑,请不要做

假设您将维度与行混为一谈...那么您就明白了。只需捕获列(对你来说 listNum),然后使用另一个 int 变量捕获行。然后像往常一样创建数组。

int[][] customArray = new int[listNum][rowNum];

下面是创建 jagged array 整数的示例:

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("How many lists do you want to create? ");
    int listNum = input.nextInt();

    int[][] data = new int[listNum][];

    // get number of entries for each row
    for (int i=0; i<data.length; i++) {
        System.out.print("How many entries are in list No. "+(i+1)+" ? ");
        int numEntries = input.nextInt();
        data[i] = new int[numEntries];
    }

    // demonstrate that it worked:
    for (int i=0; i<data.length; i++) {
        for(int j=0; j<data[i].length; j++) {
            System.out.print(data[i][j] + " ");
        }
        System.out.println();
    }
} 

示例输出:

How many lists do you want to create? 3
How many entries are in list No. 1 ? 5
How many entries are in list No. 2 ? 7
How many entries are in list No. 3 ? 2
0 0 0 0 0 
0 0 0 0 0 0 0 
0 0