java - 如何在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。
解决方案
推荐阅读
- c# - 网站发布后,如何使用文件路径打开文件?
- sql - SQL:无法创建函数返回表。“表在此位置无效,期待:位、布尔值、布尔值......”
- r - 使用 ggplot 更改堆叠图形的位置
- angular - 使用 ngModel 将对象(取自后端 API)从 HTML 传递到 Typescript
- arrays - 需要帮助在终止前删除指针
- arrays - 如何使用逻辑应用将所有 Azure AD 用户组成员存储在数组中
- azure-devops - 如何在 VSTS 构建过程中创建 zip 之前修改 Publish Artifact 文件夹 $(build.artifactstagingdirectory)?
- ios - 为什么我不能在嵌套调用尝试中创建 url
- javascript - 使用 javascript 从我的域中清除所有 cookie
- php - 触发特定按钮并使用 Prestashop 运行一些代码