您好,我的二维数组列打印了两次。请帮我识别错误的代码。以下是我尝试过的:
public class ArrayExercise {
public static void main(String[] args){
String[][] myArray = {
{"Philippines", "South Korea", "Japan", "Israel"}, // Countries
{"Manila", "Seoul", "Tokyo", "Jerusalem" } // capital cities
};
String outputString = String.format("%16s\t%9s", "Country", "City" );
System.out.println(outputString);
for( int col = 0; col < myArray[0].length; ++col ){
for( int row = 0; row < myArray.length; ++row ){
System.out.printf( "%16s\t%9s", myArray[0][col], myArray[1][col] );
}
System.out.println();
}
}
}
这让我抓狂,我似乎找不到错误:(
最佳答案
在内部循环中,您将打印两行: - myArray[0][col], myArray[1][col]
然后你使用内部循环迭代该事物两次:-
for( int row = 0; row < myArray.length; ++row ){
System.out.printf( "%16s\t%9s", myArray[0][col], myArray[1][col] );
}
您需要删除此内部循环:-
for( int col = 0; col < myArray[0].length; ++col ){
System.out.printf( "%16s\t%9s", myArray[0][col], myArray[1][col] );
System.out.println();
}
关于Java 2d 数组列打印两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12727122/