1

I am having trouble getting my 2D array to print side by side values taking the first array row value index 0 and matching it to the 2nd row array index 0 and continuing on in a vertical list. As it stands, my code compiles and just prints the entire arrays in a horizontal fashion on two lines. Basically, I would like the end result to be formatted like this:

Admin | Password1
Vale.Vicky | BruceIsTheBat!
Lane.Lois | FlyMeToTheMoon1234
Kent.Clark | PhoneBoothsSmell
Wayne.Bruce | ThisBat4You99

...and so on.

public class PasswordArrays {                   // start of class

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

    String [][] idArray = {
            {"Admin", "Vale.Vicky", "Lane.Lois", "Kent.Clark", "Wayne.Bruce", "Parker.Peter", "Rogers.Steve", "Luther.Lex", "Osborn.Harry","Prince.Diana", "Linda Zoel"},
            {"Password1", "BruceIsTheBat!", "FlyMeToTheMoon1234", "PhoneBoothsSmell","ThisBat4You99", "webSlinger","ShieldEnthusiast", "HairClub4Men", "GoblinGoober", "WonderWonderWho?", "WhoIsLindaZoel?"}
            };

    printArray(idArray);

} //End of main
public static void printArray(String a [][]) {      //start of printArray method

    for (int row=0; row < a.length ; row++) {       // start of row for loop    

        for (int column = 0; column < a [row].length; column++) {       //start of column for loop

            System.out.print(a[row][column] + " ");

        } // End of column for loop

        System.out.println();

    } // End of row for loop


} // End of printArray method

} //End of class

I know there's got to be an answer already for this somewhere but I have been unsuccessful in finding it. Any help is greatly appreciated.

2
  • 1
    It looks like you need to learn to use a debugger. Please help yourself to some complementary debugging techniques. If you still have issues afterwards, please feel free to come back with a more specific question. Commented Feb 21, 2018 at 21:17
  • IntStream.range(0, idArray[0].length).map(i -> idArray[0][i] + " | " + idArray[1][i]).forEach(System.out::println); Commented Feb 21, 2018 at 21:32

3 Answers 3

3

A 2D array could be iterated in two ways:

  1. Row wise

  2. Column wise

As per your expected result, what you would want to do is iterate column wise rather than row wise. Here's a solution:

public static void printArray(String a [][]) {

    for(int col=0; col < a[0].length; col++) {
        for (int row = 0; row < a.length; row++) {
            if (row!=a.length-1) {
                System.out.print(a[row][col] + "|");
            }
            else {
                System.out.print(a[row][col]);
            }
        }
        System.out.println();
    }
}

Helpful Link: Iterate through multi-dimensional array

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

Comments

3
  • you are traversing your 2D array incorrectly
  • you can try this for your array:

    if(a.length > 0){
      for(int i = 0; i < a[0].length; i++){
        for(int j = 0;j < a.length; j++){
          System.out.print(a[j][i]+" ");
        }
        System.out.println("");
      }
    }
    

1 Comment

replace your nested for loop with this and it will work
0

Structure

Are you sure that you understood the structure of your 2d-array? You only have two rows but multiple columns (the array contains 2 arrays containing multiple elements each).

The structure is

idArray = { /* firstArray, secondArray */ }

idArray[0] = { /* Names */ }
idArray[1] = { /* Passwords */ }

Solution

You only need one iteration from int i = 0; to i < idArray[0].length. After that always pair the content of idArray[0][i] with idArray[1][i], that's all.

final int[][] idArray = ...

// Variant 1: Regular for-loop
for (int i = 0; i < idArray[0].length; i++) {
    System.out.println(idArray[0][i] + " | " + idArray[1][i];
}

// Variant 2: Stream solution
IntStream.range(0, idArray[0].length)                 // IntStream
    .map(i -> idArray[0][i] + " | " + idArray[1][i])  // Stream<String>
    .forEach(System.out::println);

Note that idArray[0].length and idArray[1].length should of course be equal.


Notes

Probably you are better off using proper OOP, creating classes for each Account containing name and password fields and then using a List<Account> and toString for Account or something like that.

public class Account {
    private final String mName;
    private final String mPassword;

    public Account(final String name, final String password) {
        this.mName = name;
        this.mPassword = password;
    }

    public String getName() {
        return this.mName;
    }

    public String getPassword() {
        return this.mPassword;
    }

    @Override
    public String toString() {
        return this.getName() + " | " + this.getPassword();
    }
}

And then use it like

final List<Account> accounts = new ArrayList<>();
accounts.add(new Account("Admin", "Password1"));
...

// Variant 1: Enhanced for-loop 'foreach'
for (final Account account : accounts) {
    System.out.println(account);
}

// Variant 2: The same using streams
accounts.forEach(System.out::println);

// Variant 3: Using Lists 'toString'
System.out.println(accounts);

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.