Hello this is just a simple 2d array problem, I’d like to display my 2 array elements in 2 columns like this:
Countries Cities
Phils Manila
SK Seoul
Japan Tokyo
Israel Jerusalem
Here is my tried code:
public class ArrayExercise {
public static void main(String[] args){
String[][] myArray = {
{"Philippines", "South Korea", "Japan", "Israel"}, // Countries
{"Manila", "Seoul", "Tokyo", "Jerusalem" } // capital cities
};
System.out.print( "Countries\tCities\n" );
for( int row = 0; row < myArray.length; ++row ){
System.out.print( "" );
for( int col = 0; col < myArray[row].length; ++col ){
System.out.print( "" + myArray[row][col] + "\t" );
}
}
System.out.println( "" );
}
}
But I can’t get it to display in 2 columns..Any help is surely appreciated. Thanks guys 🙂
How about iterating col first and then row..
Explanation:
Your two dimensional array is like that
Philippines[0,0] South Korea[0,1] Japan[0,2] Israel[0,3]
Manila[1,0] Seoul[1,1] Tokyo[1,2] Jerusalem[1,3]
But your wants is here[row, col] is previous index.
So iterate outerloop with column.
Inside innerloop, iterate with row and use “\t” to separate.
After inner loop, I print a new line.