我会尽力解释这个问题。我正在从我的表格附加行的文件中读取分数。该线包括日期,主队,得分,客队,得分。 我收集的数据是胜利,主场胜利和平局。 以下代码完美无缺
JButton viewStatsButton = new JButton(new AbstractAction("VIEW STATS")
{
public void actionPerformed( ActionEvent e )
{
int homeScore = 0;
int awayScore = 0;
int homeWins = 0;
int awayWins = 0;
int scoreDraw = 0;
String line = null;
String output;
String matchDay;
@SuppressWarnings("unused")
String homeTeam;
@SuppressWarnings("unused")
String awayTeam;
String file = "scores.dat";
StringTokenizer tokenizer;
FileReader fileReader = null;
try
{
fileReader = new FileReader (file);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
BufferedReader inFile = new BufferedReader (fileReader);
try
{
line = inFile.readLine();
}
catch (IOException e1)
{
e1.printStackTrace();
}
while(line != null)
{
tokenizer = new StringTokenizer(line);
matchDay = tokenizer.nextToken();
homeTeam = tokenizer.nextToken();
try
{
homeScore = Integer.parseInt(tokenizer.nextToken());
}
catch (NumberFormatException exception)
{
System.out.println("Error in input. Line ignored:");
System.out.println(line);
}
awayTeam = tokenizer.nextToken();
try
{
awayScore = Integer.parseInt(tokenizer.nextToken());
}
catch (NumberFormatException exception)
{
System.out.println("Error in input. Line ignored:");
System.out.println(line);
}
if(homeScore > awayScore)
{
homeWins++;
}
else if(awayScore > homeScore)
{
awayWins++;
}
else
{
scoreDraw++;
}
try
{
line = inFile.readLine();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
try
{
inFile.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
output = "Home Wins : "+homeWins+"\nAway Wins : "+awayWins+"\nDraws : "+scoreDraw;
JTextArea textArea = new JTextArea();
frame.getContentPane().add(textArea, BorderLayout.CENTER);
textArea.setText(output);
}
});
scorePanel.add(viewStatsButton);
}
直到球队的名字由两个字符串组成,即纽卡斯尔联队,这个问题才会浮出水面。我要做的就是像NewcastleUnited一样将两个字符串附加在一起。我试图找出令牌的长度,如果它小于3,那么我把它解析为整数,但似乎即使下一个令牌引用在if语句中它仍然移动到令牌之后。
我将不胜感激任何帮助和指导。
答案 0 :(得分:0)
尝试以下
tokenizer.nextToken()
之前,请检查tokenizer.hasMoreTokens()
以确保有令牌可供阅读if(tokenizer.hasMoreTokens()) { x = tokenizer.nextToken(); }
homeTeam = tokenizer.nextToken(); String temp = tokenizer.nextToken(); try { homeScore = Integer.parseInt(temp); } catch(Exception e) { //Comes here if temp is not an integer, so temp is second part of name homeTeam = homeTeam + " "+temp; homeScore = Integer.parseInt(tokenizer.nextToken()); } //Whatever the case, if we come here, it means both hometeam and score are assigned. ........... ........... ...........
tokenizer.hasMoreTokens()
。