JAVA二维阵列循环打印格式[0] [0],[1] [1]等

时间:2018-02-21 21:13:42

标签: java arrays string printing formatting

我无法让我的2D数组以并排值打印第一个数组行值索引0并将其与第二行数组索引0匹配并在垂直列表中继续。就目前而言,我的代码编译并在两行上以水平方式打印整个数组。基本上,我希望最终结果的格式如下:

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

......等等。

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

我知道在某个地方已经有了答案,但我找不到它。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

  • 您正在错误地遍历2D阵列
  • 你可以为你的阵列尝试这个:

    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 :(得分:2)

可以通过两种方式迭代2D数组:

  1. 明智地

  2. 专栏

  3. 根据您的预期结果,您想要做的是按列方式迭代而不是按行方式迭代。这是一个解决方案:

    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();
        }
    }
    

    有用的链接:Iterate through multi-dimensional array

答案 2 :(得分:0)

结构

您确定您了解二维阵列的结构吗?您只有两行但有多列(该数组包含2个包含多个元素的数组)。

结构是

idArray = { /* firstArray, secondArray */ }

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

解决方案

您只需要从int i = 0;i < idArray[0].length的一次迭代。之后,始终将idArray[0][i]的内容与idArray[1][i]配对,这就是全部内容。

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

请注意,idArray[0].lengthidArray[1].length当然应该相同。

备注

可能最好使用正确的OOP,为包含Accountname字段的每个password创建类,然后使用List<Account>toString Account或类似的东西。

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();
    }
}

然后像

一样使用它
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);