多维数组不断重复

Multidimensional Array keeps repeating

提问人:SCoffers Rel 提问时间:7/4/2023 最后编辑:SCoffers Rel 更新时间:7/6/2023 访问量:66

问:

我是 java 的新手,不幸的是,我正在为此苦苦挣扎。我似乎无法让数组在每次迭代中停止重复。我在输出中组合线条时也遇到了问题。我尝试使用扫描仪,但我似乎也无法让它工作。

这是我尝试过的:

`// Online Java Compiler

使用此编辑器在线编写、编译和运行 Java 代码

import java.util.Scanner;

class ArrayStudies {

  public static void main(String[] args) {
    //* Define and initialize the ID Array *//
    int[] id = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    //* Define the UserID Array *//
    String[] userid = new String[10];
    //* Initialize the Names Array *//
    userid[0] = "Admin";
    userid[1] = "Vale.Vicky";
    userid[2] = "Lane.Lois";
    userid[3] = "Kent.Clark";
    userid[4] = "Wayne.Bruce";
    userid[5] = "Parker.Peter";
    userid[6] = "Rogers.Steve";
    userid[7] = "Luther.Lex";
    userid[8] = "Osborn.Harry";
    userid[9] = "Prince.Diana";
    //* Define the Password Array *//
    String[] password = new String[10];
    //* Initialize the Password Array *//
    password[0] = "Password1";
    password[1] = "ZZZZZZZ";
    password[2] = "VVVVVV";
    password[3] = "AAAAAA";
    password[4] = "FFFFFFFF";
    password[5] = "RRRRRRR";
    password[6] = "QQQQQQ";
    password[7] = "GGGGGG";
    password[8] = "YYYYYY";
    password[9] = "LLLLLLL";

    //*Use data to Create Multidemensional Array*//
    for (int l = 0; l < id.length; l++) {
      for (int i = 0; i < userid.length; i++)
        System.out.println("ID: " + id[i] + " " + "UserID: " + userid[i] + " " + "Password:" + " " + password[i]);
    }
  }
}
Java 多维数组 java.util.scanner

评论

3赞 Andy Turner 7/4/2023
为什么决定使用嵌套的 for 循环?我建议删除外部的(等)。for (int l
2赞 Chaosfire 7/4/2023
您的数组具有 1 维,因此不需要嵌套循环。
1赞 Old Dog Programmer 7/5/2023
您的代码不显示任何多维数组。使用多维数组的代码应如下所示:...您正在做的是使用并行数组。在您的例子中,您有 3 个单维数组。使用面向对象语言的程序员往往不喜欢并行数组。Foo [][] foo2D;Foo [][][] foo 3D;Foo [][][][] foo4D;
1赞 Old Dog Programmer 7/5/2023
题外话:使用类的一个优点是,与一个实体相关的值可以粘附到单个 Object 中。您可以通过创建类来避免并行数组:。这样,您可以有一个数组:class Person { int id; String name; String password; Person (int id, String name, String pass) { this.id = id; this.name = name; this.password = pass; } // getters & setters, if any ... }Person [] = { new Person (0, "Admin","Password1"), new Person (1, "Vale.Vicky", "ZZZZZZZ"), ... }
1赞 Mark Rotteveel 7/5/2023
@OldDogProgrammer Java 记录使它变得更加简单,您就完成了。record Person(int id, String name, String pass) { }

答:

0赞 Reilas 7/5/2023 #1

使用一个 for 循环

//*Use data to Create Multidemensional Array*//
String[][] strings = new String[10][2];
for (int index = 0; index < 10; index++) {
    strings[index][0] = userid[index];
    strings[index][1] = password[index];
}

输出

strings[0] = [Admin, Password1]
strings[1] = [Vale.Vicky, ZZZZZZZ]
strings[2] = [Lane.Lois, VVVVVV]
strings[3] = [Kent.Clark, AAAAAA]
strings[4] = [Wayne.Bruce, FFFFFFFF]
strings[5] = [Parker.Peter, RRRRRRR]
strings[6] = [Rogers.Steve, QQQQQQ]
strings[7] = [Luther.Lex, GGGGGG]
strings[8] = [Osborn.Harry, YYYYYY]
strings[9] = [Prince.Diana, LLLLLLL]