首页 > 解决方案 > 如何在for循环中将变量放入映射中

问题描述

我正在尝试分配从文本文件中获取的键和值并将其解析为变量到映射中,但它一直给我一个 NullPointeException。调试时,它告诉我在分配它们时它们具有值,因此我不确定问题出在哪里。我从另一种方法传递分数图,然后将其写入文件,我试图从文件中获取数据并将其放回地图中。

我已经移动它试图在键和值具有分配的所有点将键和值添加到映射中。

for (int index = score.indexOf("=") - 1; index >= 0; index = score.indexOf("=", index + 1)) {
    int j = 0;
    int i = 1;
    int l = 1;
    int k = 2;
    String key = null;
    int value = 0;
    score = score.replaceAll("\\=", "");
    while (j < score.length() && i <= score.length() && l < score.length() && k <= score.length()) {

        if (score.substring(j, i).matches("[^0-9]") || score.substring(l, k).matches("[1-9]")) {

            key = score.substring(j, i);
            if (score.substring(l, k).matches("[1-9]")) {
                String v = score.substring(l, k);
                value = Integer.parseInt(v);
            }

            if (key.matches("[^0-9]") && !key.matches("\\s")) {
                System.out.println(key); //For testing if variable is there
                System.out.println(value); // testing if variable is there.
                scores.put(key, value); // NPE here
           }

预期映射包含文件中的新键和值,尝试执行此操作时会收到 NullPointerException。

标签: javaloopsnullpointerexceptionmapsput

解决方案


推荐阅读