0

我必须输出每行最多 4 个数组值的数组,但我不知道如何将其转换为二维数组。破折号之后是我遇到麻烦的地方。如果我不将其输出为 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("}");

   }
}
4

3 回答 3

0

无需仔细查看您的代码:要在控制台上的多行输出一维数组,请考虑以下内容:

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');
}
于 2013-11-10T17:18:41.290 回答
0
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("}");
 }
于 2013-11-10T17:18:57.640 回答
0

要将 1d 数组输出为 2d,一行上最多有 4 个值,请使用以下代码:

for (int i = 0; i < array.length; i++) {
    System.out.print(array[i] + " ");
    if ((i+1) % 4 == 0)
        System.out.println();
}
于 2013-11-10T17:19:37.553 回答