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.
Related
Introduction
Hi guys, I am new to Java programming. Forgive me if I may have ask a repeated
question. Have tried to look around for similar answers on stack but cant.
Have been stuck on this for few days.
I want to read the last two digits of a text file and validate using regex. If its greater than 70
System should print "They are speeding.";
This would be the draft of the the text file.
AB12345-60
AB22345-60
AB32345-80
Sample Java code:
import java.io.*;
class Main {
private final int LinesToRead = 3;
private final String REGEX = ".{2}\d{5}[-]\d{2}";
public void testFile(String fileName) {
int lineCounter = 1;
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
while ((line != null) && (lineCounter <= LinesToRead)) {
if (line.matches(REGEX)) {
System.out.println("They are not speeding");
}
else {
System.out.println("They are speeding");
}
line = br.readLine();
lineCounter++;
}
} catch (Exception ex) {
System.out.println("Exception occurred: " + ex.toString());
}
}
public static void main(String[] args) {
Main vtf = new Main();
vtf.testFile("Data.txt");
} }
I suggest just doing a string split to isolate the final speed number, and then check it via an inequality:
while ((line != null) && (lineCounter <= LinesToRead)) {
int speed = Integer.parseInt(line.split("-")[1]);
if (speed > 70) {
System.out.println("They are speeding");
}
else {
System.out.println("They are not speeding");
}
line = br.readLine();
lineCounter++;
}
the task is to find number of occurrences of a particular word in a file
that person wrote herself.
public void reader() {
BufferedReader myR = myReader("enter the name of a file: ");
int count = 0;
String substring = readLine("enter the string to count for entry: ");
try {
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
myR.close();
} catch (IOException e) {
throw new ErrorException(e);
}
println("number of words is: " + count);
}
private BufferedReader myReader(String prompt) {
BufferedReader rd = null;
while (rd == null) {
try {
String name = readLine(prompt);
rd = new BufferedReader(new FileReader(name));
} catch (FileNotFoundException e) {
println("wrong file entered");
// e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return rd;
}
So the problem is that i can't figure out what to do if in my text file number of word i was checking is 4, but the code prints 671
the problem lies in this loop:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
now suppose your bufferedReader reads a line "hie i am user".
the size of this string is 13 so string.length(); would return 13.
that means you would be checking the same line for 13 iterations for your match.
So, suppose if you are looking for a match say "user" then checking for "user" on the same line for 13 times would make your count go up to 13.
you can replace the above code with this code:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
String[] slist = s.split(" ");
for(int j=0; j<slist.length(); j++){
if(slist[j].contains(substring)){
count++;
}
}
}
ohh!! you should have mentioned that you wanna do it without using an array.
this snippet should help you:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.equals(" ")){
String temp = s.substring(j+1, s.length());
String word = temp.substring(0,temp.indexOf(" ")-1);
if(temp.equalsIgnoringCases(word)){
count++;
}
}
}
}
now what i am doing here is first of all i am looking for a space in the whole string and upon finding one, I am extracting a substring starting from the index next to the index of space to the end of the string.
Now from this extracted substring, I am further extracting a substring from index zero up till the first space. this string is essentially a word suitable for comparison.
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 want combine the two methods Just some error in my document parser, frequencyCounter and parseFiles thsi code.
I want all of frequencyCounter should be a function that should be executed from within parseFiles, and relevant information don't worry about the file's content should be passed to doSomething so that it knows what to print.
Right now I'm just keep messing up on how to put these two methods together, please give some advices
this is my main class:
public class Yolo {
public static void frodo() throws Exception {
int n; // number of keywords
Scanner sc = new Scanner(System.in);
System.out.println("number of keywords : ");
n = sc.nextInt();
for (int j = 0; j <= n; j++) {
Scanner scan = new Scanner(System.in);
System.out.println("give the testword : ");
String testWord = scan.next();
System.out.println(testWord);
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
// System.out.println(strLine);
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The code below gives you this output:
Professor frequency: 54
engineering frequency: 188
data frequency: 2
mining frequency: 2
research frequency: 9
Though this is only for doc1, you've to add a loop to iterate on all the 5 documents.
public class yolo {
public static void frodo() throws Exception {
String[] keywords = { "Professor" , "engineering" , "data" , "mining" , "research"};
for(int i=0; i< keywords.length; i++){
String testWord = keywords[i];
File document = new File("path//to//doc1.txt");
boolean check = true;
try {
FileInputStream fstream = new FileInputStream(document);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
strLine = br.readLine();
// Read File Line By Line
int count = 0;
while ((strLine = br.readLine()) != null) {
// check to see whether testWord occurs at least once in the
// line of text
check = strLine.toLowerCase().contains(testWord.toLowerCase());
if (check) {
// get the line
String[] lineWords = strLine.split("\\s+");
count++;
}
}
System.out.println(testWord + "frequency: " + count);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
hope this helps!
I have the sample.txt which contains 100 Integers (range 0-9) in every line formatted like this:
9 2 0 3 4 1 0 7 5 3 7 8 6 2 0 1 4 4 5 9 0 3 2 1 7 (etc... 100 numbers)
I want to scan the file and put every line into a 10x10 table. So:
public void loadTableFromFile(String filepath){
try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {
String line;
while (s.hasNextLine()) {
// WHAT HERE? THIS BLOCK DOES NOT WORK
/* if (s.hasNextInt()) {
//take int and put it in the table in the right position procedure
} else {
s.next();
} */
// END OF NOT WORKING BLOCK
}
} catch (FileNotFoundException e){
}
}
How about something like this?
public void loadTableFromFile(String filepath) {
Scanner s = null; // Our scanner.
try {
s = new Scanner(new BufferedReader(
new FileReader(filepath))); // get it from the file.
String line;
while (s.hasNextLine()) { // while we have lines.
line = s.nextLine(); // get a line.
StringTokenizer st = new StringTokenizer(line, " ");
int i = 0;
while (st.hasMoreTokens()) {
if (i != 0) {
System.out.print(' '); // add a space between elements.
}
System.out.print(st.nextToken().trim()); // print the next element.
i++;
if (i % 10 == 0) { // Add a new line every ten elements.
System.out.println();
}
}
System.out.println(); // between lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (s != null)
s.close();
}
}
Here is a solution that reads the line of the file into an array of strings using the split by whitespace method, and then reads them in using a for loop. I threw any exceptions that might have occurred in the method declaration, alternatively, use the try catch loop as above (might be better design, not sure about that.)
public void loadTableFromFile(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String[] line = br.readLine().split(" ");
br.close(); // file only has 1 line with 100 integers
int[][] mydata = new int[10][10];
for(int i = 0; i < line.length; i++) {
mydata[i % 10][(int) (i / 10)] = Integer.parseInt(line[i]);
}
}
Now, if the file has more than one line, you could instead read the entire file line by line, and then use the above idea like this:
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line1;
while((line1 = br.readLine()) != null) {
String[] line = line1.split(" ");
... // do above stuff of reading in 1 line here
}
br.close();
Try,
try (Scanner s = new Scanner(new BufferedReader(new FileReader(filepath)))) {
String line;
while (s.hasNextLine()) {
String[] strArr=line.split(" ");
for(int i=0;i<strArr.length;i++){
System.out.print(" "+strArr[i]);
if((i+1)%10==0){
System.out.println();
}
}
}
} catch (FileNotFoundException e){
}