3 回答
TA贡献2016条经验 获得超9个赞
在您的代码中,您尚未初始化补救措施 HashSet(这就是它在第 14 行抛出 NullPointerException 的原因)。第二个问题是: i 递增 1 并且您没有检查 pats 数组的大小( i > parts.length) 。我编辑了你的代码:
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
TA贡献1752条经验 获得超4个赞
你在这里有几个问题:
不需要内部 while 循环 (
while (fin.hasNext()) {
) - 而是使用 `for(int i=1; iHashSet <String> remedies = null;
- 这意味着集合未初始化,我们不能将项目放入其中 - 需要更改为:HashSet<String> remedies = new HashSet<>();
更好的做法
close()
是在finally
零件中的文件'display' 方法将在打印前删除该行(如果它超过 80 个字符)。
附加字符串时最好使用 StringBuilder
所以更正后的代码是:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
添加回答
举报