如何读取文件并保存到哈希图中,然后将第一个元素保存为键,其余元素保存在一个集合中?

我正在阅读一个带有疾病名称及其治疗方法的文件。因此,我想将名称保存为键,并将补救措施保存在一组中作为值。我怎么能达到那个?我的代码中似乎存在一些问题。


public static HashMap<String,Set<String>> disease = new HashMap <> ();


public static void main(String[] args) {


Scanner fin = null;

    try {


        fin = new Scanner (new File ("diseases.txt"));

        while (fin.hasNextLine()) {

            HashSet <String> remedies = null;

            String [] parts = fin.nextLine().split(",");            

            int i = 1;

            while (fin.hasNext()) {

                remedies.add(parts[i].trim());

                i++;

            }


            disease.put(parts[0],remedies);



        }

        fin.close();

        }catch(Exception e) {

        System.out.println("Error: " + e.getMessage());

    }

    finally {

        try {fin.close();} catch(Exception e) {}

    }

    Set <String> result = disease.get("thrombosis");

    display(result);


    public static <T> void display (Set<T> items) {

    if (items == null)

        return;

    int LEN = 80;

    String line = "[";

    for (T item:items) {

        line+= item.toString() + ",";

        if (line.length()> LEN) {

            line = "";

        }

    }

    System.out.println(line + "]");

}

这是我的代码


癌症、疼痛、肿胀、出血、体重减轻


痛风、疼痛、甲型肝炎肿胀、变色、不适、疲倦


血栓形成,心率加快


糖尿病,尿频


这是txt包含的内容。


慕尼黑5688855
浏览 119回答 3
3回答

慕沐林林

在您的代码中,您尚未初始化补救措施 HashSet(这就是它在第 14 行抛出 NullPointerException 的原因)。第二个问题是: i 递增 1 并且您没有检查 pats 数组的大小( i > parts.length) 。我编辑了你的代码:&nbsp; &nbsp; Scanner fin = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; fin = new Scanner(new File("diseases.txt"));&nbsp; &nbsp; &nbsp; &nbsp; while (fin.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HashSet<String> remedies = new HashSet<String>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] parts = fin.nextLine().split(",");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int i = 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (fin.hasNext()&&parts.length>i) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; remedies.add(parts[i].trim());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; disease.put(parts[0], remedies);&nbsp; &nbsp; &nbsp; &nbsp; }

温温酱

你在这里有几个问题:不需要内部 while 循环 (&nbsp;while (fin.hasNext()) {) - 而是使用 `for(int i=1; iHashSet <String> remedies = null;&nbsp;- 这意味着集合未初始化,我们不能将项目放入其中 - 需要更改为:&nbsp;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 {&nbsp; &nbsp; public static HashMap<String,Set<String>> disease = new HashMap<>();&nbsp; &nbsp; private static int LINE_LENGTH = 80;&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; Scanner fin = null;&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fin = new Scanner(new File("diseases.txt"));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (fin.hasNextLine()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; HashSet<String> remedies = new HashSet<>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String[] parts = fin.nextLine().split(",");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; disease.put(parts[0], remedies);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 1; i < parts.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; remedies.add(parts[i].trim());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Error: " + e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fin.close();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Error when closing file: " + e.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Set<String> result = disease.get("thrombosis");&nbsp; &nbsp; &nbsp; &nbsp; display(result);&nbsp; &nbsp; }&nbsp; &nbsp; public static <T> void display (Set<T> items) {&nbsp; &nbsp; &nbsp; &nbsp; if (items == null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder line = new StringBuilder("[");&nbsp; &nbsp; &nbsp; &nbsp; int currentLength = 1; // start from 1 because of the '[' char&nbsp; &nbsp; &nbsp; &nbsp; for (T item:items) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String itemStr = item.toString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; line.append(itemStr).append(",");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentLength += itemStr.length() + 1; // itemStr length plus the ',' char&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (currentLength >= LINE_LENGTH) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; line.append("\n");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; currentLength = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // replace last ',' with ']'&nbsp; &nbsp; &nbsp; &nbsp; line.replace(line.length() - 1, line.length(), "]");&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(line.toString());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java