【问题标题】:JAVA 2D Array Loop Print Formatting [0][0], [1][1], etcJAVA 2D 数组循环打印格式 [0][0]、[1][1] 等
【发布时间】:2018-02-21 21:13:41
【问题描述】:

我无法让我的二维数组并排打印取第一个数组行值索引 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

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

【问题讨论】:

  • 看来你需要学习使用调试器了。请帮助自己一些complementary debugging techniques。如果您之后仍有问题,请随时回来提出更具体的问题。
  • IntStream.range(0, idArray[0].length).map(i -&gt; idArray[0][i] + " | " + idArray[1][i]).forEach(System.out::println);

标签: java arrays string printing formatting


【解决方案1】:

二维数组可以通过两种方式迭代:

  1. 逐行

  2. 按列

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

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】:
    • 您正在错误地遍历二维数组
    • 您可以为您的阵列尝试这个:

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

    【讨论】:

    • 用这个替换你的嵌套for循环,它会工作
    【解决方案3】:

    结构

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

    结构是

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

    解决方案

    您只需要从int i = 0; 到i &lt; 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].length 和idArray[1].length 当然应该相等。


    注意事项

    您最好使用适当的 OOP,为每个包含 name 和 password 字段的 Account 创建类,然后为 Account 使用 List&lt;Account&gt; 和 toString 或类似的东西。

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

    【讨论】:

      猜你喜欢
      • 2019-12-03
      • 1970-01-01
      • 2019-12-23
      • 2017-11-28
      • 2017-12-11
      • 1970-01-01
      • 2012-12-16
      • 2018-08-31
      • 1970-01-01
      相关资源
      最近更新 更多