1

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

3
  • +1 Almost everyone has answered incorrectly. Commented Oct 4, 2012 at 11:37
  • @AmitD swemon's answer is correct. I tried his code and it worked well for me. Commented Oct 4, 2012 at 11:44
  • Yes. It is only correct answer. because outer loop is on col Commented Oct 4, 2012 at 11:46

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

I think that's what the first System.out.print("") in the loop was suppose to be
@MadProgrammer: Yes, quite possibly.
This will not work array is of length 2 line will get printed for only 2 times.
Hello David, in what loop are you referring to that I need to print a new line?
2

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..

8 Comments

This will not work array is of length 2 line will get printed for only 2 times
@AmitD.. What?? Did you see the code clearly?? sysout() is not inside the inner loop.. It's outside the inner loop..
It has only two rows so outer loop will iterate only two times so it print line only two times.
It's not printing in 2 columns :(
@AmitD.. Common man.. of course I didn't checked on the logic what OP is using.. I just copy pasted the code, and told him where he was wrong... As he said he was not able to print them on new lines..
|
1

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.

1 Comment

I added my explanation.. hope it helps you.
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.