【发布时间】:2014-09-13 14:59:45
【问题描述】:
我已经编写了一些代码来处理两个级别的嵌入式循环。我在主要方法结束之前的最后一段代码有问题,我只想在对角线上打印元素。代码打印值,但不是我想要查看它们的方式。当我们只写矩阵的 digonlas 时,我被困在要给出的选项卡的数量上,以便以纸上显示的方式打印值。
这是我的代码:
package com.codopedia.java7.sep2014;
/**
*
* @author www.codopedia.com
*/
public class TwoDArrayExp1 {
public static void main(String args[]) {
int row = 5, column = 5, k = 0;
int my2dArray1[][] = new int[row][column];//5 rows and 5 columns
//Initializing the array elements to zero
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
my2dArray1[i][j] = k;
k++;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
System.out.print("(" + (i + 1) + " , " + (j + 1) + ")" + " = " + " " + my2dArray1[i][j] + "\t");
}
System.out.println();//För att börja en ny rad
}
System.out.println();
System.out.println();
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (j > i) {//When column is greater than row (Printing on the digagonal and below it only.)
continue;//Stop printing at this row and go to the next row
}
//System.out.print("(" + (i + 1) + " , " + (j + 1) + ")" + " = " + " " + my2dArray1[i][j] + "\t");
System.out.print(my2dArray1[i][j] + "\t");
}
System.out.println();//För att börja nya rad.
}
System.out.println();
System.out.println();
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (j >= i) { //Priniting on the diagonal and above it only.
System.out.print(my2dArray1[i][j] + "\t");
}
}
System.out.println();//För att börja nya rad.
for (int x = 0; x <= i; x++) {
System.out.print("\t");
}
}
System.out.println();
System.out.println();
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if (i == j) {
System.out.print(my2dArray1[i][j]);
}
}
System.out.println();//För att börja nya rad.
for (int x = 0; x <= i; x++) {
System.out.print("\t");//Moving to the place where we want to print
}
}
System.out.println();
System.out.println();
for (int i = 0; i < row; i++) {
int tab = 0;
for (int j = 0; j < column; j++) {
//setting the tab with each pass of the external loop
//i.e, when we move to the next row. The while loop does the trick
while (tab != (column - (i + 1))) {
System.out.print("\t");
tab++;
}
if (j == (column - (i + 1))) {
System.out.print(my2dArray1[i][j]);
System.out.println();//För att börja nya rad.
}
}
}
System.out.println();
System.out.println();
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if ((j == i) || (j == (column - (i + 1)))) {
System.out.print(my2dArray1[i][j]);
for (int tabs = 0; tabs <= (column - (i + 1)); tabs++) {
System.out.print("\t");
}
}
}
System.out.println();//För att börja nya rad.
}
}//method main ends here.
}//class TwoDArrayExp1 ends here.
【问题讨论】: