我正在尝试创建一个程序来跟踪大学球队及其体育记录(胜利,损失,岁月)。我想使用Map(我选择了TreeMap)和Set(我选择了TreeSet)。我想从文件中读取团队并根据输入更新数据库。例如,线路:1975年:加州大学洛杉矶分校:布朗将增加对加州大学洛杉矶分校的胜利,增加布朗的损失,并将1975年加入两队。
树形图的关键是大学名称。值是一个名为TeamInfo的对象
import java.util.TreeSet;
class TeamInfo {
int wins = 0;
int losses = 0;
TreeSet years;
TeamInfo(int wins, int losses, String year) {
// provide constructor code here
this.wins = wins;
this.losses = losses;
years = new TreeSet();
}
void incrementWins() {
wins++;
}
void incrementLosses() {
losses++;
}
void addYear(String aYear) {
// provide addYear code here
years.add(aYear);
}
public String toString() {
// provide toString() code here
return " Wins: " + wins + " Losses: " + losses + "\n" + "Years: " +
years.toString();
}
} // end TeamInfo
理想情况下,从文件中读取后,我应该得到输出:
姓名:加州大学洛杉矶分校获胜:1次失败:0
姓名:布朗赢:0损失:1
当我输入这样的内容时,我的问题出现了:
1939:维拉诺瓦:棕色
1940:棕色:维拉诺瓦
1940:棕色:维拉诺瓦
我得到这样的输出:
姓名:布朗赢:2次失败:0
年:[1940]
姓名:布朗赢:0损失:1
年:[1939]
姓名:维拉诺瓦获胜:1次失误:1次
年:[1939年,1940年]
姓名:维拉诺瓦获胜:0次失误:1次
年:[1940]
输出应该类似于:
姓名:布朗获胜:2次失败:1次
姓名:维拉诺瓦获胜:1次失误:2次
每支球队的胜负记录都有单独的记录,当时只有一条记录同时有胜负。我已经盯着我的代码几个小时了,似乎无法理解为什么会这样做。谁能告诉我我犯了什么错误以及为什么会这样?
谢谢!
这是我的主要课程:
import java.util.TreeMap;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
public class Records {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
File input = new File("C:\\Users\\Christian\\Desktop\\C code\\input4.txt");
Scanner test = new Scanner(input).useDelimiter("[:\n]");
TeamInfo tester;
String year ="";
String winner="";
String loser="";
TreeMap records = new TreeMap();
TeamInfo temp = new TeamInfo(0,0,"");
while(test.hasNext())
{
year = test.next();
winner = test.next();
loser = test.next();
/*search(test.next)
increment win
*/
if(!records.containsKey(winner))
{
TeamInfo firstRecord = new TeamInfo(0,0,"");
firstRecord.incrementWins();
firstRecord.addYear(year);
records.put(winner, firstRecord);
// System.out.println("First iteration of " + winner);
}
else if(records.containsKey(winner))
{
temp = (TeamInfo)records.get(winner);
temp.incrementWins();
temp.addYear(year);
records.replace(winner, temp);
// System.out.println("FOUND " + winner);
}
/*
search(test.next)*/
if(!records.containsKey(loser))
{
TeamInfo firstRecord = new TeamInfo(0,0,"");
firstRecord.incrementLosses();
firstRecord.addYear(year);
records.put(loser, firstRecord);
// System.out.println("First iteration of " + loser);
}
else if(records.containsKey(loser))
{
temp = (TeamInfo)records.get(loser);
temp.incrementLosses();
temp.addYear(year);
records.replace(loser, temp);
// System.out.println("FOUND " + loser);
}
/*increment loss
*/
}
while(!records.isEmpty())
{
temp = (TeamInfo)records.get(records.firstKey());
System.out.println("Name: " + records.firstKey().toString() + temp.toString());
records.remove(records.firstKey());
}
}
}