Phinx Velasco
Phinx Velasco

Reputation: 23

Displaying Elements of Multidimensional Array of Strings [Java]

I am new in programming. Need to have your advise to shorten improve my code below.

public class Exercise4 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String[][] info = {{"010","John","Male","21"},
                            {"011","Mary","Female","25"},
                            {"012","Joseph","Male","24"},
                            {"013","Peter","Male","22"}};

        for(int i = 0; i < 4; i++) {

            for(int j = 0; j < 4; j++) {

                if(j == 0) {
                    System.out.print("ID: ");
                } else if(j == 1) {
                    System.out.print("Name: ");
                } else if(j == 2) {
                    System.out.print("Gender: ");
                } else if(j == 3) {
                    System.out.print("Age: ");
                }

                System.out.println(info[i][j]);
            }
            System.out.println();
        }

    }

}

This will display the following output. Is there any way to improve/shorten my code? I think there's a way to shorten it but I just couldn't figure it out.

Output:

Output

Upvotes: 2

Views: 63

Answers (2)

Scary Wombat
Scary Wombat

Reputation: 44834

As you are using hard-coded array bounds, You could also do it as given below:

for(int i = 0; i < info.length; i++) {
        System.out.printf ("%nID: %s%nName: %s%nGender: %s%nAge:%s%n", 
                           info[i][0], info[i][1], info[i][2], info[i][3]);
}

Upvotes: 2

Derrick
Derrick

Reputation: 4427

You can do something like this -

List<String> headerList = Arrays.asList(new String[]{"ID","Name","Gender","Age"});
List<String[]> infoList = Arrays.asList(info);
for(String[] s: infoList){
  int count = 0;
  for(String header : headerList){
    System.out.println(header+": "+s[count]);
    count++;
    }
 }

Note: Headers length and rows length should be same.

Upvotes: 0

Related Questions