I've tried in vain to compare scores in my application with scores already saved in a separate text file. Comparing the score is easy enough when strings aren't involved but when I save the score and assign it a name, the program doesn't work as it cannot parse strings & integers.
Example text file:
Name, 8
Name, 1
Name, 4
Code I'm using to compare:
int highScore = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = reader.readLine();
while (line != null)
{
try {
int score = Integer.parseInt(line.trim());
if (score > highScore)
{
highScore = score;
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR");
}
The rest of the code is fine and the score is generated as the game finishes comparing it to the score in the file, it just generates a 0 value when comparing as it reads the string and doesn't work. I'm not sure on how to use scanners/delimiters.
EDIT:
I'd like the program to execute and show the name of the user which got that highscore. So the desired output would be;
The all time high score was 8 by Name1
Currently it only says the highscore (following Michu93's input).
Run the below program. It will give you desired output. Please correct the other things, I just concentrated on output.
public class Test {
static int highScore = 0;
static String highscorer = "";
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("src/com/test/package1/txt.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
try {
String[] parts = line.split(",");
int tempScore = Integer.parseInt(parts[1].trim());
String tempHigScorer = (parts[0]);
if (tempScore > highScore) {
highScore = tempScore;
highscorer = tempHigScorer;
}
} catch (NumberFormatException e1) {
// handle NumberFormatException if any
}
}
reader.close();
} catch (IOException ex) {
System.err.println("ERROR");
}
System.out.println("The all time high score was " + highScore + " by name " + highscorer);
}
}
Remove digits from string and parse it to int:
int score = Integer.valueOf(line.replaceAll("[^\\d.]", ""));
#Edit
int highScore = 0;
String name = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = reader.readLine();
while (line != null) {
try {
int score = Integer.parseInt(line.split(" ")[1]);
if (score > highScore) {
highScore = score;
name = line.split(" ")[0].replace(",", "");
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
line = reader.readLine();
}
System.out.println(String.format("The all time high score was %s by %s", highscore, name));
} catch (IOException ex) {
System.err.println("ERROR");
} finally {
reader.close(); // close stream always in finnaly block or use try with resources!!!
}
Observe that when you read a whole line you are getting a String with both Name and the Integer you want to get. I'd do the following:
int highScore = 0;
String name = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("txt.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
try {
String[] parts = line.split(",");
if(parts.length > 1){
int score = Integer.parseInt(parts[1].trim());
if (score > highScore) {
highScore = score;
name = line[0];
}
}
} catch (NumberFormatException e1) {
//ignore invalid scores
//System.err.println("ignoring invalid score: " + line);
}
}
System.out.println("The all time high score was %s by %s", highScore, name);
reader.close();
Related
Already fixed. Thanks for Mas & ruhul for observing my bugs.
I was trying to read a text file twice, named stationary.txt. The contents of the file has three columns such as the amount, the name of product and the total price.
What I am trying to do first is by averaging each product's price by reading line by line. Then I closed the Buffered and then open it again and read. The second reading takes a variable average and compares each product's price line by line. If line 1 is over the average, then write it into dearer.txt, otherwise write it into cheap.txt
Here is the stationary.txt
1 Highlighter 5.99
2 Pen 9.00
3 Eraser 5.00
4 DrawingPin 2.75
5 Highlighter 10.99
6 FountainPen 20.50
7 Pencil 14.50
Below is the source code
import java.util.*;
import java.io.*;
public class Ques {
public static void main(String[] args) throws FileNotFoundException {
double average = 0;
File inFile = new File("stationary.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
File outFilel = new File("dearer.txt");
FileOutputStream outFileStreaml = new FileOutputStream(outFilel);
PrintWriter outStream1 = new PrintWriter(outFileStreaml);
File outFile2 = new File("cheap.txt");
FileOutputStream outFileStream2 = new FileOutputStream(outFile2);
PrintWriter outStream2 = new PrintWriter(outFileStream2);
computeAverage(bufReader, outStream1, outStream2, average);
}
public static void computeAverage(BufferedReader bufReader, PrintWriter outStream1, PrintWriter outStream2, double average) {
String line = "";
double mark = 0;
double sum = 0;
int count = 0;
try {
bufReader.readLine();
while ((line = bufReader.readLine()) != null) {
String [] data = line.split(" ");
mark = Double.parseDouble(data[2]);
sum += mark;
count++;
}
average = sum / count;
compareMark(outStream1, outStream2, average);
} catch (NumberFormatException | IOException e) {
System.out.println(e);
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
}
}
public static void compareMark(PrintWriter outStream1, PrintWriter outStream2, double average) throws FileNotFoundException {
File inFile = new File("stationary.txt");
FileReader fileReader = new FileReader(inFile);
BufferedReader bufReader = new BufferedReader(fileReader);
String line = " ";
double sum = 0;
double mark = 0;
int count = 0;
try {
double ave = (double) Math.round(average * 100) / 100;
System.out.println("another " + ave);
bufReader.readLine();
while ((line = bufReader.readLine()) != null) {
System.out.println(line);
String [] data = line.split(" ");
mark = Double.parseDouble(data[2]);
if (mark > ave) {
System.out.println("Over");
outStream1.write(line);
} else {
System.out.println("Less");
outStream2.write(line);
}
}
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException ex) {
System.out.println(ex);
} finally {
if (bufReader != null) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
The source code is perfectly working, just that I received 0 bytes of both files after executing reading twice (first, doing average and last, doing comparison). Why is that? what am I doing wrong here?
Thank you for your kind help.
Your code is not correct and does not compile. But the main flaws are the following:
Your Double.parseDouble(data[2]) shouldn't work with your 4th line of data. Better use Double.parseDouble(data[data.length - 1])
Remove the readLine()-calls in front of the while-loop.
Write the lines including a line separator.
Close the OutStreams
The Data File that you have provided have the columns seperated by a space. As the 2nd Column has data which contains spaces, the convertion of data[2] to double will trigger an exception. Which will make the program to close the buffers and exit.
Use Commas to seperate column data.
Use better exception handling to find exceptions easily.
All you need is to close those output stream. As you are using bufferredWriter and not flushing it after each write you need to close those output-stream. which will write back those lines or datas into the file. Here is an example how you can do it:
Example 1: using flush().
....
outStream1.write(line);
outStream1.flush();
} else {
System.out.println("Less");
outStream2.write(line);
outStream2.flush();
}
Example 2: most efficient (either way you need to close those buffer too like bufReader.close())
...
} catch (IOException e) {
System.out.println(e);
} catch (NumberFormatException ex) {
System.out.println(ex);
} finally {
// add try catch.
outStream2.close();
outStream1.close();
if (bufReader != null ... ) {
try {
bufReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As requested, an example using List
First a class to hold the stationary data, must be completed:
public class Stationary {
private final int id; // or String if desired
private final String name;
private final double mark; // BigDecimal would be better for money
public Stationary(int id, String name, double mark) {
// TODO error checking
this.id = id;
...
}
public int getId() {
return id;
}
... // TODO other getters
// TODO equals, hashCode, toString
}
and to read the file:
public List<Stationary> read(File file) {
List<Stationary> list= new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
// TODO parse line into id, name, mark
list.add(new Stationary(id, name, mark);
}
}
return list;
}
now the list can be used as needed, e.g. average:
List<Stationary> stationaries = read(STATIONARY_FILE);
...
for (Stationary stationary : stationaries) {
sum += stationary.getMark();
count += 1;
}
...
streams not used to keep it simple
I created a java file called Product.java. I also created a text file called Items.txt. Basically when the user enter the word using sequential search to search the data what they are looking from Items.txt. My main problem is when I enter 3 to display all the records or enter x to exit the program, it keeps on looping. But I don't how to resolve this problem. Can anyone solved this for me?
Items.txt
1000|Cream of Wheat|Normal Size|Breakfast|NTUC|5|3.00
1001|Ayam Brand|Small Size|Canned|NTUC|4|4.00
Product.java
import java.io.*;
import java.util.*;
public class Product {
public static void main(String[] args) {
ArrayList<Item> prdct = new ArrayList<Item>();
String inFile = "items.txt";
String line = "";
FileReader fr = null;
BufferedReader br = null;
StringTokenizer tokenizer;
int quantity;
String id, brandname, desc, category, supplier;
float price;
try{
fr = new FileReader(inFile);
br = new BufferedReader(fr);
line = br.readLine();
while(line!=null)
{
tokenizer = new StringTokenizer(line,"|");
id = tokenizer.nextToken();
brandname = tokenizer.nextToken();
desc = tokenizer.nextToken();
category = tokenizer.nextToken();
supplier = tokenizer.nextToken();
quantity = Integer.parseInt(tokenizer.nextToken());
price = Float.parseFloat(tokenizer.nextToken());
Item itm = new Item(id,brandname,desc,category,supplier,quantity,price);
prdct.add(itm);
line = br.readLine();
}
br.close();
}
catch(FileNotFoundException e){
System.out.println("The file " + inFile + " was not found.");
}
catch(IOException e){
System.out.println("Reading error!");
}
finally
{
if (fr!=null){
try
{
fr.close();
}
catch(IOException e)
{
System.out.println("Error closing file!");
}
}
}
String INPUT_PROMPT = "\nPlease enter 3 to display all records, 4 to insert record, 5 to remove old records " + "or enter 'x' to quit.";
System.out.println(INPUT_PROMPT);
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader (System.in));
line = reader.readLine();
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
while("3".equals(line))
{
for(int i=0; i<prdct.size(); i++)
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
while(!line.equals("x"))
{
System.out.println(INPUT_PROMPT);
line=reader.readLine();
}
}
catch(Exception e){
System.out.println("Input Error!");
}
}
}
The problem is with this loop:
while(reader != null)
{
for(int i=0; i<prdct.size(); i++)
{
if(prdct.get(i).id.contains(line) || prdct.get(i).brandname.contains(line) || prdct.get(i).desc.contains(line)
|| prdct.get(i).category.contains(line) || prdct.get(i).supplier.contains(line))
{
System.out.println(prdct.get(i));
}
System.out.println(INPUT_PROMPT);
line = reader.readLine();
}
}
It keeps on looping while reader is not null and it will never be. You might want to try checking something else that suits your problem better, maybe:
While(!line.equals("3"))
While(!line.equals("x"))
While(line != null)
Otherwise, even if there is an 'x', '3' or simply nothing, still (reader != null) and therefore the loop is infinite.
I suspect that the newline character is what causes the comparison to fail.
Instead of checking if:
"3".equals(line)
Try:
"3".equals(line.trim())
Same applies to the following comparison.
Try changing this..
line = reader.readLine();
while(reader != null)
{
to this..
line = reader.readLine();
while(line != null)
{
You are looping on the reader being not null, which it always will be.
you have to define these functions:
public void showAllRecords() {
// show all record here
}
public void insertRecord() {
// insert record here
}
public void removeRecord() {
// insert record here
}
public void exit() {
// insert record here
}
then
do{
System.out.println(INPUT_PROMPT);
switch(line)
{
case "3":
showAllRecords();
break;
case "4":
insertRecord();
break;
case "5":
removeRecord();
}
}while(!line.equals('x'));
I've written a program that reads in a text file to show football scores, now the text file is arranged so that it has errors included and I'm trying to write a program to count these errors. The text file is arranged like so:
Hull City : Sunderland : 2 : 3
Chelsea : Manchester City :1
Fulham : Leeds United : 1 : 2
Wigan : Tottenham : 1 : x
: :2:0
So the above has missing team names, missing scores and some scores replaced with an X. I can't for the life of me figure out how to introduce a counter to count the number of errors, any idea on a starting point/solution would be much appreciated, thanks!
Here is my full code:
Main:
public class main {
public static void main(String[] args) {
String userInput;
readFile readScores = new readFile();
do
{
userInput = readScores.getUserInput();
if(userInput.equalsIgnoreCase("S"))
readScores.printScores();
readScores.totalGoals();
readScores.errorCount();
} while (!userInput.equalsIgnoreCase("E"));
System.out.println("****************Exiting application****************");
System.exit(0);
}
}
Readfile Class:
public class readFile {
String [] stringArr;
Scanner scan = new Scanner(System.in);
public String getUserInput()
{
String userInput;
System.out.println("Select your option:\nS - Show Scores \nE - Exit");
userInput = scan.nextLine();
return (userInput);
}
public void printScores()
{
String sep = ":";
File inputfile = new File ("P:/SD/Assignment1/results2.txt");
String line = "";
try {
Scanner filescan = new Scanner(inputfile);
while(filescan.hasNext())
{
line = filescan.nextLine();
stringArr = line.split(sep);
if(stringArr.length == 4)
{
System.out.println(stringArr[0]+"\t [" +stringArr[2]+"]\t|" + stringArr[1]+"\t["+ stringArr[3]+" ]\n");
}
else
{
throw new IllegalArgumentException("String " + line + " does not contain " + sep);
}
}
filescan.close();
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
public void totalGoals()
{
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
System.out.println(stringArr[i]);
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
public void errorCount()
{
String line;
int errorCount=0;
String[] strArr;
try
{
BufferedReader br = new BufferedReader(new FileReader("P:/SD/Assignment1/results2.txt"));
while(line = br.readLine() != null)
{
strArr = line.split(":");
if(strArr.length==4){
if(strArr[1].trim().isEmpty()) errorCount++;
if(strArr[2].trim().isEmpty()) errorCount++;
if(strArr[3].trim().indexOf("x")>=0) errorCount++;
if(strArr[4].trim().indexOf("x")>=0) errorCount++;
}
}
}
catch(Exception e){
//error handling
}
System.out.println("Error count: "+errorCount);
}
}
UPDATE::
public void errorCount()
{
String line;
int errorCount=0;
String[] strArr;
String[] parts = line.split(":"); <--- ERROR IS HERE
if (parts.length != 4) {
errorCount++;
}
for (String part : parts) {
if (part.trim().isEmpty()) {
errorCount++;
break;
}
}
if (!(isNumeric(parts[2].trim()) && isNumeric(parts[3].trim()))) { //counts one error, otherwise, check each one of them and if both are not numeric, count this as two errors
errorCount++;
// continue with the following line
}
}
I would suggest something like that:
String line;
int errorCount=0;
String[] strArr;
try{
BufferedReader br = new BufferedReader(new FileReader(yourTextFile));
while((line = br.readLine()) != null){
strArr = line.split(":");
if(strArr.length==4){
if(strArr[0].trim().isEmpty()) errorCount++;
if(strArr[1].trim().isEmpty()) errorCount++;
if(strArr[2].trim().indexOf("x")>=0) errorCount++;
if(strArr[3].trim().indexOf("x")>=0) errorCount++;
}
else errorCount++;
}
}
catch(Exception e){
//error handling
}
System.out.println("Error count: "+errorCount);
You could check the lines against a regular expression. Each non matching line contains an error.
A starting point for the regular expression :
/(.+) : (.+) : (\d+) : (\d+)/
The parenthesis allow you to get the team names and the scores.
int errorCounter = 0; //initialize the errorCounter to zero
try{
BufferedReader br = new BufferedReader(new FileReader(yourTextFile));
while((line = br.readLine()) != null){ //read the file line by line
//Check that each line is split into 4 parts (delimited by ':')
String[] parts = line.split(":");
if (parts.length != 4) {
errorCounter++;
continue; //continue with the following line
}
// Then, check if some of the parts are null, like that:
for (String part : parts) {
if (part.trim().isEmpty()) {
errorCounter++;
}
}
//Finally, you can check if the last two parts contain numbers, using [this `isNumeric()` method][2], like that:
if (!(isNumeric(parts[2].trim())) { //checks if the third part is a number
errorCounter++;
}
if (!(isNumeric(parts[3].trim())) { //checks if the last part is numeric
errorCounter++;
}
} catch(IOException ex) {
System.err.println(ex);
}
The isNumeric() method can be found here.
Note that this solution counts multiple errors on the same line. If you want to count one error per line, you could simply use the one-liner that Lorenz Meyer suggests.
I have a program I'm writing for class, and I'm stuck on the very last part. Here's what it requests, and what I'm stuck at:
Display an error if the file does not exist or the format is
incorrect.
The formatting of the input is along the lines of:
Name;Service;Price;Date
or
Bob Smith;Dinner;52.35;04-01-2014
And my code so far:
package school;
import java.util.*;
import java.io.*;
public class HotelSales{
public static void main(String[] args){
try {
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
// I assume the format check would go here?
String[] array = new String[48];
double conferenceTotal = 0;
double dinnerTotal = 0;
double lodgingTotal = 0;
String line = "";
while((line = br.readLine()) != null){
array = line.split(";");
if(array[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(array[2]);
}
}
System.out.println("The totals for the sales are: \n");
System.out.printf("Conference Total: $%-5.2f\n", conferenceTotal);
System.out.printf("Dinner Total: $%-5.2f\n", dinnerTotal);
System.out.printf("Lodging Total: $%-5.2f\n", lodgingTotal);
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("The totals for the sales are: ");
bw.newLine();
bw.newLine();
bw.write("Conference Total: $" + String.format("%-5.2f",conferenceTotal));
bw.newLine();
bw.write("Dinner Total: $" + String.format("%-5.2f",dinnerTotal));
bw.newLine();
bw.write("Lodging Total: $" + String.format("%-5.2f",lodgingTotal));
br.close();
bw.close();
} catch (InputMismatchException e) { //And that this is the proper catch right?
System.out.print("Wrong input file format.\n");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.print("Sorry, the file was not found.\n");
e.printStackTrace();
} catch (IOException e) {
System.out.print("Oops! I/O Exception.\n");
e.printStackTrace();
}
}
}
Thanks! :)
this should work:
while((line = br.readLine()) != null){
String [] array = line.split(";");
if ( array.length != 4 ) {
throw new InputMismatchException( "Invalid ... blah blah, expected 4 elements, found " + array.length );
}
try {
if(array[1].equals("Conference")) {
conferenceTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Dinner")) {
dinnerTotal += Double.parseDouble(array[2]);
} else if(array[1].equals("Lodging")) {
lodgingTotal += Double.parseDouble(array[2]);
}
} catch ( NumberFormatException nfe ) {
throw new InputMismatchException( nfe );
}
}
and remove the line:
String[] array = new String[48];
If your input file is not separated by ;'s, then when you attempt to Double.parseDouble(array[2]), you'll get an ArrayIndexOutOfBoundsException or a NullPointerException because your array will be of size 1.
while ((line = br.readLine()) != null)
{
array = line.split(";");
if (array.length != 4)
{
throw new InputMismatchException("Invalid ... blah blah, expected 4 elements, found " + array.length);
}
try
{
if (array[1].equals("Conference"))
{
conferenceTotal += Double.parseDouble(array[2]);
}
else if (array[1].equals("Dinner"))
{
dinnerTotal += Double.parseDouble(array[2]);
}
else if (array[1].equals("Lodging"))
{
lodgingTotal += Double.parseDouble(array[2]);
}
}
catch (ArrayIndexOutOfBoundsExceptione aioobe)
{
throw new InputMismatchException(aioobe);
}
I will try to explain this as much as I can. I am reading scores from a file onto which my form appends lines. The line consists of a date, home team, score, away team, score.
The stats I gather is away wins, home wins and draws.
The following code works perfectly
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);
}
The problem does not come to light until the name of team is made out of two strings i.e.Newcastle United. What I had to do was append the two strings together like NewcastleUnited. I have tried to find out the length of the token and if it's less than 3 then i take it and parse it as integer but it seems that even if the next token reference is in an if statement it still moves to the token after it.
I would appreciate any help and guidance.
Try following
Before calling tokenizer.nextToken() check tokenizer.hasMoreTokens() to ensure that there is a token to read
if(tokenizer.hasMoreTokens())
{
x = tokenizer.nextToken();
}
After reading team name(first part) check whether next part is integer if it is, treat it as score, otherwise append it to team name.
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.
...........
...........
...........
Don't forgot to check tokenizer.hasMoreTokens() if you are not sure whether there is a token.