使用Scanner从ArrayList到二维数组的字符串

时间:2015-11-01 07:32:39

标签: java arrays string loops int

我正在使用Eclipse而我正在尝试使用字符串:

1 2 3 4

出一个ArrayList:

ArrayList strings = new ArrayList<>();

并将每个数字存储为二维数组:

int size = (int) strings.get(0); // Represents the number of rows
int stringList[][] = new int[size][];

// Store results in a two dimensional array
for(int i = 0; i < size; i++){
    int index = i + 1; 
    String fish = (String) strings.get(index);

    Scanner npt = new Scanner(fish);

    for(int j = 0; npt.hasNext(); j++) {
        size[i][j] = Integer.parseInt(npt.next());
    }
}

这是导致错误的部分:

// ERROR: The type of the expression must be an array type but it resolved to int
size[i][j] = Integer.parseInt(npt.next());

2 个答案:

答案 0 :(得分:1)

stringsraw type。让我们从修复 1

开始
List<String> strings = new ArrayList<>();

然后你可以使用Integer.parseInt(String) 解析 2 String添加到int

int size = Intger.parseInt(strings.get(0));

然后

中不需要演员
String fish = (String) strings.get(index);

您可以使用

String fish = strings.get(index);

1 并编程到List界面。
2 Not cast

答案 1 :(得分:0)

你可能意味着

stringList[i][j] = Integer.parseInt(npt.next());

虽然这也不起作用,除非你正确初始化stringList数组。

您必须使用类似stringList[i]的内容初始化i(对于每个stringList[i] = new String[someLength];),但我不确定您应该使用哪个长度。