当前位置: 首页 > 知识库问答 >
问题:

创建并填充HashMap

林鸿彩
2023-03-14

第一个类称为FileReader,它读取一个逐行写入的txt文件,我们需要的每个字段都用“;”分隔,例如(“哥伦比亚大学”;“美国”;78.86;2012)。每行包含2个字符串(大学名和国家)和2个数字(分数和年份)。FileReader类在读取txt文件后,在ArrayList中返回其内容。

该作业的第二个类称为UniversityScores,它有4个字段(uniname、country、score、year)、一个构造函数、所有字段的访问器方法和一个toString方法。

第三节课是我们节目的核心。这个类叫做FileEditor,它创建一个HashMap >,其中键是每个对象的year字段,我猜值是行的其余部分。我的问题是用正确的方式填充hashmap。 list

另外,我最后的第4个类叫做FileWriter,它创建一个新的txt并在其中写入。除了我的FileEditor类之外,我的所有类都正常工作。任何需要的帮助。提前谢谢!

编辑我应该写一些其他的方法以及。目前,我的问题是FileEditor类。我还发布了包含main函数的TestFiles类。

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

class FileReader{

private String fileName;
private Scanner scanner;
private File file;
private ArrayList<String> arrayList;
private String line;

public FileReader(String otherFileName){
    this.fileName = otherFileName;
    this.file = new File(fileName);
}

public boolean initReader(){
    try {
        scanner = new Scanner(file);
    } 
    catch (FileNotFoundException e) {
        System.out.println("Just caught a FileNotFoundException.");
    }

    if(file.exists()){
        return true;
    }
    else{
        return false;
    }
}

public ArrayList<String> readFile(){
    this.arrayList = new ArrayList<String>();
    while (scanner.hasNextLine()) {
        this.line = scanner.nextLine();
        arrayList.add(line);
    }
    arrayList.remove(0);
    //System.out.println(arrayList);
    return arrayList;
}

public void closeReader(){
    scanner.close();
    System.out.println("Scanner closed");
}
}

这是一个很好的例子

import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

class FileWriter{

private String path;
private PrintWriter writer;
private File outputFile;

public FileWriter(String otherPath){
    this.path = otherPath;
    this.outputFile = new File(path);
}

public boolean initWriter(){
    try{
        writer = new PrintWriter(path);
    }
    catch (FileNotFoundException e){
        System.out.println("just caught an exception");
    }

    if(outputFile.exists()){
        return true;
    }
    else{
        return false;
    }   
}

public void writeFile(){
    writer.println("The first line");
    writer.println("The second line");
    writer.println("Christos");
}

public void closeWriter(){
    writer.close();
    System.out.println("Writer closed");
}
}
class UniversityScore{

private String name;
private String country;
private double score;
private int year;

public UniversityScore(String otherName, String otherCountry, double otherScore, int otherYear){
    this.name = otherName;
    this.country = otherCountry;
    this.score = otherScore;
    this.year = otherYear;
}

public String getName(){
    return name;
}

public String getCountry(){
    return country;
}

public double getScore(){
    return score;
}

public int getYear(){
    return year;
}

public String toString(){
    String outputString = name + "\t" + country + "\t" + score + "\t" + year;
    return outputString;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

class FileEditor{

private HashMap<Integer, ArrayList<UniversityScore>> scores = new HashMap<Integer, ArrayList<UniversityScore>>();
private ArrayList<String> lines;

public FileEditor(ArrayList<String> otherLines){
    this.lines = otherLines;
}

public void fillHashMap(){
   // that's where I need help
}
public class TestFiles {
public static void main(String[] args){
    FileReader reader = new FileReader("universities.txt");
    if(reader.initReader()){
        FileEditor editor = new FileEditor(reader.readFile());
        reader.closeReader();
        editor.fillHashMap();
        FileWriter writer = new FileWriter("universities_2015_output.txt");
        if(writer.initWriter()){
            writer.writeFile(editor.getScoresOfYear(2015));
            writer.closeWriter();
        }
        else{
            System.out.println("Error creating file");
        }
        System.out.println("Average university score of year 2015: "+editor.getAverageOfYear(2015));
        System.out.println("Min university score of year 2015: "+editor.getMinOfYear(2015));
        System.out.println("Max university score of year 2015: "+editor.getMaxOfYear(2015));
    }
    else{
        System.out.println("Error opening file");
    }
}

}

共有1个答案

伍心水
2023-03-14

您将需要一种将行解析为universityscore对象的方法。

现在您已经拥有了所有的分数,您可以根据它们的年份值(可能是score,但类型不匹配,也没有实际意义)将其添加到您的地图中,例如:

for(String line : lines){
      String[] vals = line.split(";");
      UniversityScore score = new UniversityScore(vals[0],vals[1],Double.parseDouble(vals[2]),Integer.parseInt(vals[3]))
      if(scores.containsKey(score.getYear()){ // If the key exists
         scores.get(score.getYear()).add(score);
      }else{ // If the key doesn't exist, it must be created and added to the map
         ArrayList<UniversityScore> newList = new ArrayList<>();
         newList.add(score);
         scores.put(score.getYear(), newList)
      }
    }

我注意到您的地图有一个integer键,它对应于分数的year属性,所以我假设地图的键是年份,而不是您建议的分数。

 类似资料:
  • 问题内容: 我想将读取Lucene索引的结果存储到jTable中,以便可以按不同的列对其进行排序。我从索引中读取具有不同频率度量的术语。 表列是这些:[字符串项] [int absFrequency] [int docFrequency] [double invFrequency] 所以我在AbstractTableModel中可以定义列名,但是我不知道如何使用以下方法的结果获取Object []

  • 问题内容: 我正在创建一个要在网页上显示的表,并且该表是由MySQL数据库中的数据填充的。我正在尝试做一些让我感到困难的事情。 首先,我试图通过JavaScript调用HTML中单独文件中存在的PHP代码。我认为我的工作正常,但是我不确定100%是否正确(因为表格不会显示)。我认为它工作正常,因为该表的 某些 代码(在PHP文件中)显示在FireBug中。 其次,我正在尝试使行交替显示颜色以便于查

  • 我在HTML正文中有一个名为RecipeContainer的div。我正在尝试使用一个API来根据用户的关键字搜索菜谱。最初,我在一个HTML中有6个DIV,它们被填充在我的javascript中,并使用CSS样式,但我认为这不再是一个有效的解决方案。 下面是我当前的代码,它试图将功能转移到完全在JS中创建的每个菜谱的平铺中: 这是每当用户点击Submit时执行的循环。实际上,我有两个问题与此相关

  • 问题内容: 我有两个表:tbl_listings,其列为:prop_id; 另一个表:tbl_bookings,其列为:prop_id,booking_date。 我想编写一个查询,计算prop_id在tbl_bookings中出现的所有时间,然后用该查询的结果填充tbl_listings中的新列。 我的查询看起来像: 但由于某种原因,我收到一条错误消息:子查询返回多于1行。我该如何解决? 问题答

  • 问题内容: 在Java中,如何创建在构建时填充的最终Set?我想做以下事情: 但是我不知道Java的正确语法。 问题答案: 试试这个成语:

  • 问题内容: 我设法根据矩阵内的一个指定数组(即数组内的数组)生成了一系列列表项。 我希望能够将一个变量(表示一个数组)传递给一个函数,以便它可以根据传递到其中的数组吐出一个无序列表,其中填充了列表项。 问题: 该函数一次只能使用一个数组 它还会在标记中产生逗号(大概是因为它将数组转换为字符串) 解决方案需要: 假设DOM中不存在无序列表 能够接受传递到它的不同阵列(,等) 生成没有逗号的列表项 J