1

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
        }
    }
Uyyyfgfar
  • 95
  • 1
  • 11
  • 1
    Read the file line by line. Split the line. Parse the contents. Work out the errors. – Boris the Spider Nov 09 '14 at 13:45
  • If I read your question right... You will want to read each line in as an "entry"... Then for each entry split by colons ":". If you don't get 4 bits... You have a "big" error... And if either of the first 2 are empty strings, you don't have a team, if either of the last 2 are not parsed as numbers (or are equal to 'x') you don't have scores. – scunliffe Nov 09 '14 at 13:48

3 Answers3

2

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);
vefthym
  • 7,422
  • 6
  • 32
  • 58
Leonard
  • 783
  • 3
  • 22
1

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.

Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
  • +1 for the simplicity! Much better than my answer by far. Adding the method that checks if the pattern is matched, would help IMHO. – vefthym Nov 09 '14 at 13:54
  • I understand what you mean! I just don't understand how I would write this in the code. New to Java so may be a little slow – Uyyyfgfar Nov 09 '14 at 13:58
  • @MattMurphy put this regex as a parameter the `line.matches()` method, where each time line is the String of the current line. If it returns false, increment the errorCounter by one. – vefthym Nov 09 '14 at 14:01
  • 1
    Nice solution but you would not be able to count multiple mistakes in one line. – Leonard Nov 09 '14 at 14:03
  • @rumo *Error* here is too vague. Counting multiple errors on one line makes only sense when you look for specific errors. – Lorenz Meyer Nov 09 '14 at 14:09
0
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.

Community
  • 1
  • 1
vefthym
  • 7,422
  • 6
  • 32
  • 58
  • hi, thanks for the reply! I'm using eclipse and it seems to have a problem with the isNumeric function, it says it's undefined for the type readFile – Uyyyfgfar Nov 09 '14 at 14:02
  • @MattMurphy did you copy if from this link: http://stackoverflow.com/a/1102916/2516301 ? If yes, put it in the same Class where your main method is and just import anything eclipse suggest you to – vefthym Nov 09 '14 at 14:05
  • I've got the numeric function working now, now another error has popped up! Where it says: String[] parts = line.split(":"); --- line is underlined and it says the local variable may have not been initialized, however it's stated above as String line; – Uyyyfgfar Nov 09 '14 at 14:11
  • That was in the link provided. line is defined exactly as in the answer of Rumo – vefthym Nov 09 '14 at 14:14
  • Yeah i used the link to get isNumeric working, and I've defined line exactly how it is in Rumo's answer, just seems to say its not initialised. I'll post the method exactly how I've got it now in my code at the top. – Uyyyfgfar Nov 09 '14 at 14:20