简体   繁体   中英

Java 2D array column

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 :)

You're not adding a newline after looping through myArray[row] . You need to add this after the loop to print a new line:

System.out.println();

In general, if you want a line-ending, don't call System.out.print("\\n") , but rather System.out.println() . System.out.println() uses the system line-ending, which isn't necessarily a newline character ( \\n ).

UPDATE :- Here's the way to print them in 2 columns: -

    String[][] myArray = {
            {"Philippines", "South Korea", "Japan", "Israel"}, // Countries
            {"Manila", "Seoul", "Tokyo", "Jerusalem" } // capital cities
    };

    int j = 0;

    while (j < myArray[0].length) {
        System.out.printf("%-15s - %-15s", myArray[0][j], myArray[1][j++]);
        System.out.println();
    }

Since you want to print values of two rows parallelly for each column..
You can iterate over columns, and print values of both the rows for that corresponding column..

NOTE :- I have used value 15 for formatting.. In general that may give you wrong result, when the length of your string (country or city) is greater than that..

For, more improvement , you can replace 15 with the length of longest country string and longest city string , from two rows..

How about iterating col first and then row..

for( int col = 0; col < myArray[0].length; ++col ){
            for( int row = 0; row < myArray.length; ++row ){
                System.out.print(myArray[row][col]);
                System.out.print("\t");
            }
            System.out.println();
        }

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.

  • Philippines[0,0] Manila[1,0]
  • South Korea[0,1] Seoul[1,1]
  • Japan[0,2] Tokyo[1,2]
  • Israel[0,3] Jerusalem[1,3]

So iterate outerloop with column. Inside innerloop, iterate with row and use "\\t" to separate. After inner loop, I print a new line.

If you know for sure you're dealing with just two lists of equal-length do:

public class ArrayExercise {
    public static void main(String[] args){
        String[][] data = {
            {"Philippines", "South Korea", "Japan", "Israel"}, // Countries                                                                                                                                                 
            {"Manila", "Seoul", "Tokyo", "Jerusalem" } // capital cities                                                                                                                                                    
        };

        System.out.print("Countries\tCities\n");
        int colLength = data[0].length;
        for (int i = 0; i < colLength; ++i) {
            System.out.printf("%s\t%s\n", data[0][i], data[1][i]);
        }
    }
}

This will give the (tabbed) output:
Countries Cities
Philippines Manila
South Korea Seoul
Japan Tokyo
Israel Jerusalem

First, you need to find out the lenght of the longest element of the first column (the countries), say the maximum length is 5, and you want to have a leading space at every line. And you also need to find the maximum lenght of the second column, say here it is 8. When you have done this, you can print the elements using a String.format :

outputString = String.format("%1$6s %2$8s\n",country, city);
System.out.println(outputString);

The formatter sets the width of the first parameter to X , so you will get a correct indentation. This will work with string of any length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM