【问题标题】:String from ArrayList to two dimensional array using Scanner使用 Scanner 从 ArrayList 到二维数组的字符串
【发布时间】:2023-04-05 15:44:01
【问题描述】:

我正在使用 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());

【问题讨论】:

  • sizeint,你不能写size[i][j]。错误信息很清楚。
  • 哇,我必须完全摆脱它,我根本没有注意到这一点。很抱歉浪费了你们的时间。

标签: java arrays string loops int


【解决方案1】:

stringsraw type。让我们从解决这个问题开始1,

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

然后你可以使用Integer.parseInt(String) 解析2Stringint 喜欢

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

那么在

中就不需要cast
String fish = (String) strings.get(index);

你可以使用

String fish = strings.get(index);

等等

1 并编程到List接口。
2 不是cast

【讨论】:

    【解决方案2】:

    你可能是说

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

    虽然这也行不通,除非您正确初始化 stringList 数组。

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

    【讨论】:

    • 是的,对不起。我没有注意到我的错误。现在很明显,但在你们指出之前我根本没有看到。
    猜你喜欢
    • 2021-06-12
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    相关资源
    最近更新 更多