存储和使用逐行读取的数据

时间:2015-06-16 21:50:57

标签: java

如果我有一个文件来阅读[顺序],那么包含两个团队及其在每一行的分数,如:

黑豹3骑士5

火箭队4泰坦队9

Anteaters 8 Yahoos 6

黑豹10泰坦3

Yahoos 4 Rockets 7

我需要考虑一种方法来跟踪每个团队及其胜负,并将其打印到新文件中。如:

团队赢得损失

黑豹1 1

火箭队0 2

我面临的问题是,我不知道如何以这样的方式存储团队名称,以便在PrintWriter读入数据时我能够将胜负添加到该团队。任何输入都会得到赞赏以及解释..这就是我到目前为止所做的。

import java.util.*; 
import java.io.*;
public class SoccerLeague
{
    public static void main(String[]args) throws IOException
    {
        File inputFile= new File("SoccerNotSorted.txt");
        Scanner input = new Scanner(inputFile);
        if(!inputFile.exists())
        {
            System.out.println("File not found");
            System.exit(0);
        }
        File outputFile= new File("SoccerSort.txt");
        PrintWriter output= new PrintWriter(outputFile);
        if (!outputFile.exists())
        {
            System.out.println("output file not found");
            System.exit(0);
        }
        while(input.hasNext())//This is where i attempted to solve the prob.
        {

            //String team1 = input.next();
            //int score1 = input.nextInt();
            //String team2= input.next();
            //int score2=input.nextInt();
            //int wins=0;
            //if(score1>score2)
            //{
            //  output.println(team1+"wins against"+team2);
            //} 
            //else()



        }
        input.close();
        output.close();

    }
}

2 个答案:

答案 0 :(得分:1)

您可能希望调查Maps以使字符串与另一段数据相关联,例如赢/输的总计。 : - )

答案 1 :(得分:0)

List<Team> allTeams = new ArrayList<Team>();
while (scanner.hasNextLine()){
    // "Panthers 3 Cavaliers 5", for example
    String teamString = scanner.nextLine();
    String[4] teamComponents = teamString.split(" ");
    Team team1 = new Team();
    team1.setName(teamComponents[0]); // sets team1 name to Panthers
    team1.setScore(Integer.valueOf(teamComponents[1]); // sets team1 score to 3
    Team team2 = new Team();
    team2.setName(teamComponents[2]); // sets team2 name to Cavaliers
    team2.setScore(Integer.valueOf(teamComponents[3]); // sets team2 score to 5
    allTeams.add(team1);
    allTeams.add(team2); // now you can access all of the Team objects created in the while loop outside of the loop, 
    // since the List was instantiated before iterating through all of the lines in your input file
} 

到循环结束时,您的列表应包含10个Team对象。 请记住,名称team1和team2是任意的,并且仅在循环内部很重要-循环外部的List对象对循环内部的变量名称一无所知。