简体   繁体   中英

Storing Scanner Input and Using

I have a java program, that reads a text file line by line, with each part of the line using a delimiter :

The data in text files can be expected to be like:

TeamOne : TeamTwo : TeamOneScore : TeamTwoScore.

I would like to create a summary, showing how many matches each team has played, and how many goals each have scored.

The data from the text file will likely have multiple instances of the same team, and preferably be able to handle creating a summary if more data is added to the text file.

What would be the best method to store each line of text, so they can be compared?

I would like it to be able to work out if a team won or lost a game, and the total amount of goals they scored.

Currently, each line is read from the text file, and stored as a string and then split into 4 sections. This all happens within a while loop, and the data is then lost when the next line is read:

fileinput = fileread.nextLine(); 
String line = fileinput;
String[] split = line.split(":");
String hometeam = split[0].trim();
String awayteam = split[1].trim();
String home_score = split[2].trim();
String away_score = split[3].trim();

So just for your last line: the data is then lost when the next line is read <-- That's clear because you define variables local to the for-loop. So for every iteration the variables will be initialized again. So here is my solution for you:

ArrayList<String[]> matches = new ArrayList<String[]>();
// open file somewhere
while(fileread.hasNextLine())
{
    String line = fileread.nextLine();
    String[] split = line.split(":");
    String[] toAdd = new String[4]
    toAdd[0] = split[0].trim();
    toAdd[1] = split[1].trim();
    toAdd[2] = split[2].trim();
    toAdd[3] = split[3].trim();
    matches.add(toAdd);
}

Now you have an ArrayList where each entry is a string array of size 4. But be aware, if you want to count the total scores, you have to cast the string to an int, because every attribute of a match is of type string (therefore a string array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM