提问者:小点点

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


如果我要[按顺序]读取一个文件,其中包含两个团队以及他们每行的分数,例如:

黑豹3骑士5

火箭4泰坦9

天线8 Yahoos 6

黑豹10泰坦3

雅虎4火箭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个答案

匿名用户

您可能希望查看地图以将字符串与另一段数据相关联,例如运行的总赢/输。:-)

匿名用户

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个团队对象。请记住,名称team1和team2是任意的,并且只在循环内部重要-循环外部的List对象对循环内部的变量名称一无所知。