我声明一个多维列表,如下所示
List<List<Integer>> ms = new ArrayList<List<Integer>>();如何使用for循环在上面的列表中以索引方式存储以下数据
1 2 3
3 2 1
4 5 6
例如:在多维数组中,我们这样做
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
ms[i][j]=sc.nextInt();
}
}发布于 2015-07-01 11:24:01
每个组的列表,如下所示
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
ArrayList<ArrayList<Integer>> array = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> subArray = null;
for(int i = 0; i < 3; ++i)
{
subArray = new ArrayList<Integer>();
for(int j = 0; j < 3; ++j)
{
subArray.add(sc.nextInt());
}
array.add(subArray);
}
for(int i = 0; i < array.size(); ++i)
{
subArray = array.get(i);
for(int j = 0; j < array.size(); ++j)
{
System.out.print(subArray.get(j)+" ");
}
System.out.println("");
}
}
}发布于 2015-07-01 09:42:01
您需要为每个组创建一个新的List,然后将每个元素添加到每个组,然后将此List添加到父(ms) List
就像..。
List<List<Integer>> ms = new ArrayList<List<Integer>>();
for (int i = 0; i < 3; i++) {
List<Integer> sublist = new ArrayList<>();
for (int j = 0; j < 3; j++) {
sublist.add(sc.nextInt());
}
ms.add(sublist);
}例如
发布于 2015-07-01 09:43:08
您需要分别初始化每个列表。
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < HEIGHT; i++) {
list.add(new ArrayList<Integer>());
for (int j = 0; j < WIDTH; j++)
list.at(i).add(scanner.nextInt());
}但是,如果您知道它将始终是3x3,我建议使用数组。
https://stackoverflow.com/questions/31151248
复制相似问题