我无法让我的二维数组并排打印值,采用第一个数组行值索引 0 并将其与第二行数组索引 0 匹配,然后在垂直列表中继续。就目前而言,我的代码编译并在两行上以水平方式打印整个数组。基本上,我希望最终结果的格式如下:
Admin | Password1
Vale.Vicky | BruceIsTheBat!
Lane.Lois | FlyMeToTheMoon1234
Kent.Clark | PhoneBoothsSmell
Wayne.Bruce | ThisBat4You99
……等等。
public class PasswordArrays { // start of class
public static void main(String[] args) { // Start of main
// TODO Auto-generated method stub
String [][] idArray = {
{"Admin", "Vale.Vicky", "Lane.Lois", "Kent.Clark", "Wayne.Bruce", "Parker.Peter", "Rogers.Steve", "Luther.Lex", "Osborn.Harry","Prince.Diana", "Linda Zoel"},
{"Password1", "BruceIsTheBat!", "FlyMeToTheMoon1234", "PhoneBoothsSmell","ThisBat4You99", "webSlinger","ShieldEnthusiast", "HairClub4Men", "GoblinGoober", "WonderWonderWho?", "WhoIsLindaZoel?"}
};
printArray(idArray);
} //End of main
public static void printArray(String a [][]) { //start of printArray method
for (int row=0; row < a.length ; row++) { // start of row for loop
for (int column = 0; column < a [row].length; column++) { //start of column for loop
System.out.print(a[row][column] + " ");
} // End of column for loop
System.out.println();
} // End of row for loop
} // End of printArray method
} //End of class
我知道某个地方已经有了这个问题的答案,但我没能找到它。非常感谢任何帮助。
最佳答案
二维数组可以通过两种方式迭代:
明智的行
列明智
根据您的预期结果,您要做的是按列而不是按行迭代。这是一个解决方案:
public static void printArray(String a [][]) {
for(int col=0; col < a[0].length; col++) {
for (int row = 0; row < a.length; row++) {
if (row!=a.length-1) {
System.out.print(a[row][col] + "|");
}
else {
System.out.print(a[row][col]);
}
}
System.out.println();
}
}
关于JAVA二维数组循环打印格式化[0][0]、[1][1]等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48915584/