PDA

View Full Version : Java Counting help




markgodley
Nov 5, 2009, 01:57 PM
Hey,

I have an assignment to do. I have to read a text file in using the scanner in java, getting it to read the football scores within the file and split them into 4 parts. So basically the files has Home team : away team : hometeam score : away team score. on one line and has multiple lines for multiple games.

I then have to re-arrange them so it displays them neatly. I also have to do the score count. I have done all this above (yay) but im really struggling with having it count if a line is valid. I have so far done it so it counts the string for each segment and if it contains <=0 characters it doesn't display the match but i need to count how many matches are invaild and how many are vaild. For example one line might have a missing score or a missing team name.

I hope this makes sense!

Here is my working code so far:

Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class roaroraors {

public static void main(String[] args) throws FileNotFoundException {


int goals = 0;
int hometeamLength;
int awayteamLength;
int homescoreLength;
int awayscoreLength; //int for away score string count


Scanner s = new Scanner(new File("Demo.txt")); // create a scanner which scans from a file

String line; // stores the each line of text read from the file

while ( s.hasNext() ) {

line = s.nextLine(); // read the next line of text from the file
String [] splitupText = line.split(":"); // split the text into multiple elements

String hometeam = splitupText [0];
String awayteam = splitupText [1];
String homescore = splitupText [2];
String awayscore = splitupText [3];

hometeamLength= hometeam.length();
awayteamLength= awayteam.length();
homescoreLength= homescore.length();
awayscoreLength= awayscore.length();

hometeam = hometeam.trim();
awayteam = awayteam.trim();
homescore = homescore.trim();
awayscore = awayscore.trim();
//System.out.println(hometeam + " [" + homescore+"] "+ "| " +awayteam+" ["+awayscore+"] ");

try { // "try" is a special statement which allows us to deal with "exceptions"

int homescoreint = Integer.parseInt(homescore); // attempt to convert the String into an Integer type value
int awayscoreint = Integer.parseInt(awayscore); // attempt to convert the String into an Integer type value

goals = goals + homescoreint + awayscoreint;
}
catch (NumberFormatException e) {

// The number did not parse for some reason


System.out.println("Invalid number entered"); //print line for invaild number entered
}
if(hometeamLength > 0 && awayteamLength > 0 && homescoreLength >0 && awayscoreLength >0) //if ALL team/score are greater than 0
System.out.println(hometeam + " [" + homescore+"] "+ "| " +awayteam+" ["+awayscore+"] "); //does this if it is greater than 0
else
System.out.println("TEAM or SCORE IS INVAILD"); //does this if it is not greater than or equal to 0

}

System.out.println("\nGoals = " + goals); // Output and End Of File message.
System.out.println("\nVaild Match Count = " ); // Output and End Of File message.
System.out.println("\nInvaild Match Count = " ); // Output and End Of File message.

}

}



lee1210
Nov 5, 2009, 02:05 PM
Not sure how precise this needs to be. i'd do this with regular expressions using Pattern:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html

If you don't want to/can't go that route, you can add after this line:
String [] splitupText = line.split(":");

A check to see what the length of splitupText is. if it's not exactly 4, failure. If it is, the first two fields should allow anything, i'd imagine, for team names. If there are parameters on team names, you can check them. You're already checking that the 3rd and 4th field are numbers by wrapping parseInt in a try...catch. That seems like pretty good validation to me. If there was a team roster, for example, you could compare your team names in fields 1 and 2 to the roster, but if not... i think that should about cover it.

As for counting... it seems pretty easy to keep a valid counter that you increment if all tests pass, and an invalid parameter that you increment in any failure condition. You should use continue to cycle your while loop in a failure condition so you don't detect multiple failures for a single line.

-Lee

markgodley
Nov 5, 2009, 02:15 PM
Cheers lee,

So if i put a loop after the splitupText

if (splitupText < 4)
System.out.println("Team or Score is Invaild");


?

Not sure how precise this needs to be. i'd do this with regular expressions using Pattern:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html

If you don't want to/can't go that route, you can add after this line:
String [] splitupText = line.split(":");

A check to see what the length of splitupText is. if it's not exactly 4, failure. If it is, the first two fields should allow anything, i'd imagine, for team names. If there are parameters on team names, you can check them. You're already checking that the 3rd and 4th field are numbers by wrapping parseInt in a try...catch. That seems like pretty good validation to me. If there was a team roster, for example, you could compare your team names in fields 1 and 2 to the roster, but if not... i think that should about cover it.

As for counting... it seems pretty easy to keep a valid counter that you increment if all tests pass, and an invalid parameter that you increment in any failure condition. You should use continue to cycle your while loop in a failure condition so you don't detect multiple failures for a single line.

-Lee

lee1210
Nov 5, 2009, 02:29 PM
Something like that... you'd do (or I'd do, i guess =) ):

if(splitupText == null) {
System.err.println("Invalid entry: " + line);
invalidCount++;
continue;
} else {
if(splitupText.length != 4) {
System.err.println("Invalid entry, wrong number of fields. Found " + splitupText.length", 4 required: " + line);
invalidCount++;
continue;
}
}


-Lee

EDIT: An if is not a loop, it is a conditional. You may have just typed that accidentally, but i wanted to mention it.

markgodley
Nov 5, 2009, 02:43 PM
cheers lee,

I added that loop after the string but i get some errors saying it cant be resolved.

code look like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class roaroraors {

public static void main(String[] args) throws FileNotFoundException {


int goals = 0;
int hometeamLength;
int awayteamLength;
int homescoreLength;
int awayscoreLength; //int for away score string count
int invalidCount;


Scanner s = new Scanner(new File("Demo.txt")); // create a scanner which scans from a file

String line; // stores the each line of text read from the file

while ( s.hasNext() ) {

line = s.nextLine(); // read the next line of text from the file
String [] splitupText = line.split(":"); // split the text into multiple elements

if(splitupText == null) {
System.err.println("Invalid entry: " + line);
invalidCount++;
continue;
} else {
if(splitupText.length != 4) {
System.err.println("Invalid entry, wrong number of fields. Found " + splitupText.length ", 4 required: " + line);
invalidCount++;
continue;
}
}


String hometeam = splitupText [0];
String awayteam = splitupText [1];
String homescore = splitupText [2];
String awayscore = splitupText [3];

hometeamLength= hometeam.length();
awayteamLength= awayteam.length();
homescoreLength= homescore.length();
awayscoreLength= awayscore.length();

hometeam = hometeam.trim();
awayteam = awayteam.trim();
homescore = homescore.trim();
awayscore = awayscore.trim();
//System.out.println(hometeam + " [" + homescore+"] "+ "| " +awayteam+" ["+awayscore+"] ");

try { // "try" is a special statement which allows us to deal with "exceptions"

int homescoreint = Integer.parseInt(homescore); // attempt to convert the String into an Integer type value
int awayscoreint = Integer.parseInt(awayscore); // attempt to convert the String into an Integer type value

goals = goals + homescoreint + awayscoreint;
}
catch (NumberFormatException e) {

// The number did not parse for some reason


System.out.println("Invalid number entered"); //print line for invaild number entered
}
if(hometeamLength > 0 && awayteamLength > 0 && homescoreLength >0 && awayscoreLength >0) //if ALL team/score are greater than 0
System.out.println(hometeam + " [" + homescore+"] "+ "| " +awayteam+" ["+awayscore+"] "); //does this if it is greater than 0
else
System.out.println("TEAM or SCORE IS INVAILD"); //does this if it is not greater than or equal to 0


}


System.out.println("\nGoals = " + goals); // Output and End Of File message.
System.out.println("\nVaild Match Count = " ); // Output and End Of File message.
System.out.println("\nInvaild Match Count = " ); // Output and End Of File message.

}

}

robbieduncan
Nov 5, 2009, 02:47 PM
You seem to be using a variable invalidCount that you have not defined anywhere.

markgodley
Nov 5, 2009, 02:49 PM
You seem to be using a variable invalidCount that you have not defined anywhere.

I did define them at the start under the other int but it was still saying it couldnt be resolved

robbieduncan
Nov 5, 2009, 02:50 PM
Instead of paraphrasing the errors could you copy/paste the exact error?

markgodley
Nov 5, 2009, 02:55 PM
Instead of paraphrasing the errors could you copy/paste the exact error?

Would help if i actually spelt invalidCount correctly lol.

Ok its nearly working.. i get an error saying:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Syntax error on token "", 4 required: "", delete this token

at roaroraors.main(roaroraors.java:34)


If i remove the ", 4 required: " it gives me 2 diff errors

robbieduncan
Nov 5, 2009, 02:57 PM
You were missing a + between a variable and String literal on that line. I added it and forgot to say. Line should be:


System.err.println("Invalid entry, wrong number of fields. Found " + splitupText.length+", 4 required: " + line);

markgodley
Nov 5, 2009, 02:59 PM
ahh yes.. it now gives me not be initialized errors again:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable invalidCount may not have been initialized
The local variable invalidCount may not have been initialized

at roaroraors.main(roaroraors.java:30)

code is:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class roaroraors {

public static void main(String[] args) throws FileNotFoundException {


int goals = 0;
int hometeamLength;
int awayteamLength;
int homescoreLength;
int awayscoreLength; //int for away score string count
int invalidCount;


Scanner s = new Scanner(new File("Demo.txt")); // create a scanner which scans from a file

String line; // stores the each line of text read from the file

while ( s.hasNext() ) {

line = s.nextLine(); // read the next line of text from the file
String [] splitupText = line.split(":"); // split the text into multiple elements

if(splitupText == null) {
System.err.println("Invalid entry: " + line);
invalidCount++;
continue;
} else {
if(splitupText.length != 4) {
System.err.println("Invalid entry, wrong number of fields. Found " + splitupText.length + ", 4 required: " + line);
invalidCount++;
continue;
}
}


String hometeam = splitupText [0];
String awayteam = splitupText [1];
String homescore = splitupText [2];
String awayscore = splitupText [3];

hometeamLength= hometeam.length();
awayteamLength= awayteam.length();
homescoreLength= homescore.length();
awayscoreLength= awayscore.length();

hometeam = hometeam.trim();
awayteam = awayteam.trim();
homescore = homescore.trim();
awayscore = awayscore.trim();
//System.out.println(hometeam + " [" + homescore+"] "+ "| " +awayteam+" ["+awayscore+"] ");

try { // "try" is a special statement which allows us to deal with "exceptions"

int homescoreint = Integer.parseInt(homescore); // attempt to convert the String into an Integer type value
int awayscoreint = Integer.parseInt(awayscore); // attempt to convert the String into an Integer type value

goals = goals + homescoreint + awayscoreint;
}
catch (NumberFormatException e) {

// The number did not parse for some reason


System.out.println("Invalid number entered"); //print line for invaild number entered
}
if(hometeamLength > 0 && awayteamLength > 0 && homescoreLength >0 && awayscoreLength >0) //if ALL team/score are greater than 0
System.out.println(hometeam + " [" + homescore+"] "+ "| " +awayteam+" ["+awayscore+"] "); //does this if it is greater than 0
else
System.out.println("TEAM or SCORE IS INVAILD"); //does this if it is not greater than or equal to 0


}


System.out.println("\nGoals = " + goals); // Output and End Of File message.
System.out.println("\nValid Match Count = " ); // Output and End Of File message.
System.out.println("\nInvalid Match Count = " ); // Output and End Of File message.

}

}

robbieduncan
Nov 5, 2009, 03:01 PM
That's because there are paths though the code where it is not set to anything. I would set it to zero right where you declare it.

markgodley
Nov 5, 2009, 03:14 PM
thanks its working. However instead of it displaying "team or score is invalid" i need it to count so it is simply displayed as a number at the bottom like i have set the system.out println.

I.e The total number of invalid matches = 5
The total number of valid matches = 30

robbieduncan
Nov 5, 2009, 03:15 PM
Then I suggest you trace the code manually (pencil and paper) and work out where you've gone wrong.

lee1210
Nov 5, 2009, 03:29 PM
Where in your code do you know that you have successfully parsed a line? Declare a new variable to track valid lines, and increment it there.

Everywhere else, where there is failure, you need to increment invalidCount (and add a continue so you cycle your loop, as mentioned earlier). Then outside of your while loop, you can print invalidCount and validCount as you desire. You should initialize EVERY variable to 0 explicitly, unless initialization to some other value makes more sense.

-Lee

notjustjay
Nov 5, 2009, 03:48 PM
thanks its working. However [...] i need it to [...]

I don't mean to be rude, but if you've managed to write up the code that you provided in the first post, you really should be able to run with the hints provided to you by several helpful forum members already. Things looked good for the first several posts but the last couple of rounds have me a little concerned. For example, you knew enough to declare invalidCount, but you didn't know how to resolve the error "local variable invalidCount may not have been initialized"?

Maybe you had a crappy teacher (I'm serious, as I'll explain in a moment), but there are signs to me that you don't really understand the concepts that they're trying to teach you by this exercise.

This is not to "blame" you -- I really do have a problem with schools trying to speed people through "programming exercises" without teaching the students to "think like a computer" and understand what's really going on, as opposed to copying/pasting variations of magic incantations that do the job requested. Java is a reasonable language to learn on but I'm not sure it's the best thing for a beginning programmer (BASIC does have its uses, you know! ;) ) because one tends to get confused by all the little details and lose sight of the forest for the trees, if you will.

I guess what I'm saying is, step back, think about the problem you're trying to solve, think about what you've got now and what you need to be different, and see if you can think up some pseudocode (did they teach you how to think like this?) to do what you want. Otherwise, we can provide you the bits of code, but you're not learning anything by it.

markgodley
Nov 5, 2009, 05:53 PM
Yeh your totally right about them rushing us through courses... exactly what you said also about giving you pre-written code and copy and pasting it.. its really not a great way to learn! ... our php classes are even worse!

They should really teach us a basic language like pascal.. but then again no-one would even sign up for the classes if they did...

Cheers anyway guys... im gonna try advance on my own some more.. counting loops seem to be me weakness..

lee1210
Nov 5, 2009, 06:07 PM
You're still calling if control structures loops. They are just conditional statements.

Counting is pretty straight-forward. You need a variable that you start at 0, and when some condition is met you just need to increment this with var++ or ++var, the difference is inconsequential to you now.

-Lee

P.S. A PHP class? That just doesn't even make sense to me.