简体   繁体   English

在Java中将一维数组输出为2维

[英]Output one dimensional array as 2 dimensional in java

I have to output the array with a maximum of 4 array values per line, but I can't figure out how to convert it to a 2 dimensional array. 我必须输出每行最多4个数组值的数组,但是我不知道如何将其转换为二维数组。 After the dashes is where I am having trouble. 破折号之后是我遇到麻烦的地方。 If I don't output it as a 2D array, how else would I restrict it to have only 4 values per line? 如果我不将其输出为2D数组,又如何将其限制为每行只有4个值?

public class arrayExampleB{
  public static void main(String[] args){

  int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};

  System.out.print("Pre-Swapped Array Set (linear): {");
     for(int i=0; i<=x.length-1; i++){
        if(i<x.length-1){
           System.out.print(x[i] + ", ");
        }
        else{System.out.print(x[i]);} 
     }
     System.out.print("}");

  int y = x.length-1;
  int temp = x[y];
  x[y] = x[1];
  x[1] = temp;

  int z = x.length-2;
  int temp2 = x[z];
  x[z] = x[0];
  x[0] = temp2;

  System.out.print("\nPost-Swapped Array Set (linear): {");
     for(int i=0; i<=x.length-1; i++){
        if(i<x.length-1){
           System.out.print(x[i] + ", ");
        }
        else{System.out.print(x[i]);} 
     }
     System.out.print("}");

//------------------------------------------------------------- // ------------------------------------------------ -------------

  int d = (x.length / 4) + (x.length % 4);
  int i = 0;
  int j = 0;
  int[][] t = new int[i][j];

  System.out.print("\nPre-Swapped Array Set (2D): {");
     for(i=0; i <= 4; i++){
        for(j=0; j < d; j++){
           System.out.print(t[i][j] + " ");
        }
        System.out.println();
     }
  System.out.print("}");

   }
}

Without taking too close a look on your code: To output a one dimensional array on several lines on the console consider this: 在不仔细查看代码的情况下:要在控制台的多行上输出一维数组,请考虑以下情况:

int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};

for(int i = 0; i < x.length; i++)
{
    System.out.print(x[i] + ' ');
    if( (i+1) % 4 == 0)
        System.out.print('\n');
}
int[] x = {22, 12, 28, 4, 30, 59, 17, 82, 1, 99, 47, 2, 8, 20, 80};
int[][] t = new int[4][4];

// populate 2D
int k = 0
for(i=0; i <= t.length; i++){
    for(j=0; j < t[i].length; j++){
        t[i][j] = x[k];
        k++l
    } 
}

// print
for(i=0; i <= t.length; i++){
    System.out.print("{");
    for(j=0; j < t[i].length; j++){
       System.out.print(t[i][j]);
    } 
    System.out.println("}");
 }

To output a 1d array as 2d with a max of 4 values on a line, use this code: 要将1d数组输出为2d,一行中最多包含4个值,请使用以下代码:

for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
    if ((i+1) % 4 == 0)
        System.out.println();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM