繁体   English   中英

Map中的值:无法将Integer解析为Integer

[英]value in a Map: Can't parse Integer to Integer

我有一个问题,即使我的教授在一个小时的调查后也无法解决:我有一个地图存储每个级别的高分值,其中级别保存为字符串,整数代表高分。 现在,当我尝试读取一个级别的高分时,我得到了这个非常奇怪的问题:在调用方法来读取高分时,我得到一个错误说

java.lang.String cannot be cast to java.lang.Integer

代码如下

public Map<String, Integer> highscores = new HashMap<>();
highscores.put("Level1", 35); //Example, we read it from a file
int highscore = highscores.get("Level1");

错误发生在第三行。 有谁知道为什么会这样? Integer.parseInt也不起作用,因为该方法说它需要一个String而不是一个Integer作为参数,这意味着该行的右侧实际上是一个Integer。 任何帮助是极大的赞赏。

听起来像是从文件中读取分数时,它将其作为字符串读取,然后尝试将其作为String对象而不是Integer对象粘贴到HashMap中。 这就是这个例外的来源:

java.lang.String cannot be cast to java.lang.Integer

当你说你从文件中读取它时,你确定它是一个整数而不是一个字符串吗?

代码行

int highscore = highscores.get("Level1");

做两件事,类似于以下内容:

Integer highscoreObj = highscores.get("Level1");
int highscore = highscoreObj.intValue();

当你尝试这个时会发生什么?

我刚刚在阅读文件时找到了答案,不知道我是如何忽略这个的! 它说

highscores = gson.fromJson(new BufferedReader(
                                new FileReader("ressources/highscores.json")),
                    new TypeToken<Map<String, String>>() {}.getType()); 

这显然使Map的值变为String。 将第二个参数更改为Map<String, Integer>可以解决问题。 感谢您的快速回复!

似乎你在这里提到的代码非常好,当你从文件中读取时,很可能会发生这个问题。

在将put()放入Map之前,您确定要将从文件中读取的内容转换为Integer吗?

也许你正在尝试做这样的事情:

public class Test {
    public static Map<String, Integer> highscores = new HashMap<>();

    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(Test.class.getResourceAsStream("input.txt")));

        String line = null;
        while ((line = reader.readLine()) != null) {
            String[] tokens = line.split(",");
            highscores.put(tokens[0], Integer.parseInt(tokens[1]));
        }

        System.out.println(highscores.get("Level1"));
        System.out.println(highscores.get("Level2"));
    }
}

输入文件

Level1,35
Level2,65

产量

35
65

您应该确定highscores类型的元素。类似于以下代码:

System.out.println(highscores.get("Level1").getClass());

在我的猜测中,上面代码的结果不是class java.lang.Integer ,如果结果是Class java.lang.String

您可以将代码修改为以下内容:

    Map<String, Integer> highscores = new HashMap<>();
    highscores.put("Level1", 35); //Example, we read it from a file
    Object item=highscores.get("Level1");
    if(item.getClass().equals(String.class)) {
        highscore= Integer.parseInt((String) item);
    }else if(item.getClass().equals(Integer.class)){
        highscore=(Integer)item;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM