2

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

2
  • Since this is already working code, this might be better asked at Code Review. Commented May 18, 2018 at 5:04
  • I'm voting to close this question as off-topic because the question belongs on Code Review. Commented May 18, 2018 at 5:44

2 Answers 2

2

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.