2013-11-26 83 views
0

我需要显示一个数字数组。输出必须是这样的:显示阵列ColumnWise

10 25 29 13 46 30 26 57 41 34 88 52 60 77 82 

我现在有工作,但它不是显示栏,明智的,这里是我的输出:

10 13 26 34 60 25 46 57 88 77 29 30 41 52 82 

我找到了答案类似的问题在这里,但它对于不完全相同长度的行,所以我认为它不会有帮助。

这里是我的代码(也我是新来的Java):

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

int rows = 3; 
int cols = 5; 


int intar [][] = { {10, 13, 26, 34, 60} , 
       {25, 46, 57, 88, 77}, 
       {29, 30, 41, 52, 82} }; 



for (int i = 0; i < rows; i++) { 
    for (int j = 0; j < cols; j++) { 
    System.out.print (intar[i][j] + " "); 
    } 
} 


} 
} 
+0

你应该养成使用更好的名称为循环指标的习惯。在现实世界中,我和j会导致混乱。如果您使用过rowIndex和colIndex,则可能会发现找出错误的位置更容易。 – Jason

+0

这正是我的教授要求我们使用的(i,j) –

回答

3

取代你的for循环可以做一个小的变化如下:

for (int i = 0; i < rows; i++) { 
     for (int j = 0; j < cols; j++) { 
      System.out.print(intar[i][j] + " "); 
     } 
    } 

要在控制台

for (int j = 0; j < cols; j++) { 
     for (int i = 0; i < rows; i++) { 
      System.out.print(intar[i][j] + " "); 
     } 
    } 

输出;

10 25 29 13 46 30 26 57 41 34 88 52 60 77 82 
+0

谢谢:)这工作! –

+0

欢迎。很高兴它可以帮助你。 :) – MouseLearnJava

-1

添加新行

for (int i = 0; i < rows; i++) { 
    for (int j = 0; j < cols; j++) { 
    System.out.print (intar[i][j] + " "); 
    } 
    System.out.print ("\n"); 
} 

BTW你也想做填充

+0

这不会改变数字的顺序。 – Jason

1

开关的以下两行:

for (int j = 0; j < cols; j++) { 
    for (int i = 0; i < rows; i++) { 
0

只是这个

for (int i = 0; i < cols; i++) { 
    for (int j = 0; j < rows; j++) { 
    System.out.print (intar[j][i] + " "); 
    } 
    System.out.println(); 
} 
+0

为什么downvote?我可以知道原因 – shikjohari

+0

我不是downvoter,但这可能会引发异常(超出界限)。 – Maroun

+0

@MarounMaroun它是一段正在运行的代码......我已经尝试过了。 – shikjohari

0

你靠近,这是

for (int i = 0; i < cols; i++) { 
    for (int j = 0; j < rows; j++) { 
    System.out.print(intar[j][i] + " "); 
    } 
} 
+0

这将抛出ArrayIndexOutOfBoundsException – Jason

+0

@Jason - 我跑了它... 10 25 29 13 46 30 26 57 41 34 88 52 60 77 82 –

+0

对不起,没有发现你也改变了我和j的含义。更简单的只是切换两个for循环的位置。 – Jason