【问题标题】:Getting values from a text file then having them placed into a list with no duplicates?从文本文件中获取值,然后将它们放入没有重复的列表中?
【发布时间】:2015-03-17 15:23:46
【问题描述】:

我所拥有的是一个程序,它将读取一个文本文件,该文件包含来自格式为

的文件中的数据
`FootballTeamName1 : FootballTeamName2 : FootballTeam1Score : FootballTeam2Score

目前它读入文件并将其拆分在每个冒号我想知道的是我将如何制作它,以便每次遇到一个名称时,如果没有,它将将该名称添加到列表中已经存在,或者如果确实存在,则不会创建重复值,而是会将值添加到该团队名称已存在的值中。

我目前有一个程序,可以在您搜索团队时获取值,但我想做的是使它成为可能,当用户没有指定团队时,它将使它成为可能将返回所有团队的结果。这是我目前所拥有的,它询问文件的位置并要求用户指定一个有效的文件,但我不确定如何做我想要的。

import java.awt.Desktop;
import java.io.*;
import java.util.*;

public class reader {

//used to count the number of invalid and valid matches

public static boolean verifyFormat(String[] words) {
    boolean valid = true;
    if (words.length != 4) { 
        valid = false;
    } else if (words[0].isEmpty() || words[0].matches("\\s+")) {
        valid = false;
    } else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
        valid = false;
    }

    return valid && isInteger(words[2]) && isInteger(words[3]);}

//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace

public static boolean isInteger( String input ) {
    try {
        Integer.parseInt( input );
        return true;
    }
    catch( Exception e ) {
        return false;
    }
}
//checks to make sure that the data is an integer

public static void main(String[] args) throws IOException {

      Scanner sc = new Scanner(System.in);
      while(true){ //Runs until it is specified to break

            Scanner scanner = new Scanner(System.in);


        System.out.println("Enter filename");
        String UserFile = sc.nextLine();
        File file = new File(UserFile);
        if(!file.exists()) {
          continue;
        }

        if(UserFile != null && !UserFile.isEmpty()){ 
            System.out.println("Do you want to generate plain (T)ext or (H)TML");
            String input = scanner.nextLine();
            if ( input.equalsIgnoreCase("H") ) {
                processFile(UserFile)   ;           }
            else if ( input.equalsIgnoreCase("T")){
                  processFile(UserFile);
            }
                  else{
                        System.out.println("Do you want to generate plain (T)ext or (H)TML");


                    }

        }
      }
    }

//checks how the user wants the file to be displayed 

private static void processFile(String UserFile) throws FileNotFoundException {
    String hteam;
    String ateam;
    int hscore;
    int ascore;
    int totgoals = 0;
    int gamesplayed = 0;
    int gs = 0;
    int gc = 0;
    int w = 0;
    int d = 0;
    int l = 0;
    String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.


    Scanner s = new Scanner(new BufferedReader(
            new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");

    Scanner scanner = new Scanner(System.in);

    System.out.println("Enter the name of the team you want the results for");
    String input = scanner.nextLine();


    while (s.hasNext()) {
        String line = s.nextLine();
        String[] words = line.split("\\s*:\\s*");
        //splits the file at colons

        if(verifyFormat(words)) {
            hteam = words[0];       // read the home team
            ateam = words[1];       // read the away team
            hscore = Integer.parseInt(words[2]);       //read the home team score
            totgoals = totgoals + hscore;
            ascore = Integer.parseInt(words[3]);       //read the away team score
            totgoals = totgoals + ascore;

             if ( input.equalsIgnoreCase(hteam)){
                 gamesplayed = gamesplayed + 1;
                 gs = gs + hscore;
                 gc = gc + ascore;
                 if (hscore > ascore)
                     w = w + 1;
                 else if (ascore > hscore)
                     l = l + 1;
                 else
                     d = d + 1;
             }
             else if (input.equalsIgnoreCase(ateam)){
                 gamesplayed = gamesplayed + 1;
                 gs = gs + ascore;
                 gc = gc + hscore;
                 if (hscore < ascore)
                     w = w + 1;
                 else if (ascore < hscore)
                     l = l + 1;
                 else
                     d = d + 1;
             }
        }
    }
    System.out.println(input + newLine + "--------------------------" + newLine + "Games played: " + gamesplayed +   newLine + "Games Won: " + w + newLine + "Games Drawn: " + d + newLine + "Games Lost: " + l + newLine + "Goals For: " + gs + newLine + "Goals Against: " + gc);   
}
}

【问题讨论】:

    标签: java arrays list dictionary


    【解决方案1】:

    如果您希望集合中没有重复元素,请使用 Set。 Set 是一个不包含重复元素的集合(doc here)。

    【讨论】:

      【解决方案2】:

      听起来你想要一个从团队到得分的地图,如果团队已经存在,那么从地图中获取值,以及得分。

      【讨论】:

      • 阅读后我知道如何将它添加到地图中,但我不知道如何只添加正确的,我将如何制作它以便添加第一个团队名称分数而不是将所有值添加到地图中?
      • 不确定你的意思,如果你想要一个结果列表,只需做一个从团队到分数列表的映射
      【解决方案3】:

      您可以将条目添加到 Set 中(或者如果您希望它们排序 - SortedSet)。由于 Set 只保存唯一值 - 您将始终只有每个值的一个“副本”。

      作为参考,以下代码使用 5 个值,但该集合将只有 3 个(唯一)值:

      String str = "A : B : C : B : A";
      String[] vals = str.split(":");
      SortedSet<String> myVals = new TreeSet<String>();
      for(String val : vals)
      {
          myVals.add(val.trim());
      }
      
      System.out.println("Set size: " + myVals.size());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-26
        • 2017-09-03
        • 1970-01-01
        • 2015-07-26
        • 1970-01-01
        • 2016-04-16
        • 2015-04-09
        • 2020-03-07
        相关资源
        最近更新 更多