【问题标题】:Is there a way to convert an input Matrix to an ArrayList of ArrayLists?有没有办法将输入矩阵转换为 ArrayLists 的 ArrayList?
【发布时间】:2021-04-06 02:03:57
【问题描述】:

这是一个示例输入,我想创建一个 ArrayList 的 ArrayList:

1,0,1
1,1,1
0,0,1

我有 Scanner in 保存输入,我正在考虑使用 for 循环将数字添加到使用 in.nextInt() 的 ArrayList 的 ArrayList 中。但问题是我如何找到何时应该移动到大 ArrayList 中的下一个 ArrayList?

【问题讨论】:

  • int xAxisLength = 2; int yAxisLength = 2; int zAxisLength = 2; ArrayList>> space = new ArrayList(xAxisLength); for (int i = 0; i >(yAxisLength)); for (int j = 0; j (zAxisLength)); } }

标签: java arrays matrix arraylist


【解决方案1】:

您可以在移动到下一个 ArrayList 之前定义任意数量的限制

while (condition to keep reading)
{
 for (int i = 0; i < arbitrarylimit; i++) {
   List<Integer> list = new ArrayList<Integer>();
   // read the input 
   biglist.add(list);
 }
}

或者你可以确定,如果你在一个数字之前找到一个新行,那么它应该被插入到一个新的 ArrayList 中。

while (condition to keep reading)
{
   List<Integer> list = new ArrayList<Integer>();
   String result = scanner.nextLine();
   // split result and add it to a list
   biglist.add(list);
}

【讨论】:

    【解决方案2】:

    你可以这样做。

    • 将每一行作为单行读取
    • 每个数字都可以用逗号和/或空格分隔
    • 使用流并用逗号和空格分隔它们
      将它们转换为List&lt;Integer&gt;
    • 然后将该列表添加到整个列表列表中。
    
    String line = "";
    List<List<Integer>> lists = new ArrayList<>();
    // take input until a `#` is typed on a new line.
    while (sc.hasNextLine()) {
        List<Integer> nums = Arrays.stream(line.split("[\\s,]+"))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        lists.add(nums);
    }
    lists.forEach(System.out::println);
    

    对于每行以下输入

    1 0,1
    1,1,1
    0 0 1
    

    你得到以下输出

    [1, 0, 1]
    [1, 1, 1]
    [0, 0, 1]
    
    

    【讨论】:

    • 如果我不想在输入中使用“#”怎么办?
    • 您可以使用任何字符或字符串。输入仅表示输入结束,不在其他地方使用。您还可以提示输入行数和列数。并使用那些。但是,如果您从控制台输入此内容,则需要发出输入结束信号。有时,根据操作系统,可能会使用 ctrl 字符。你想怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多