0

I'm trying to make a tiny program that will read inputs from a file and print them out if they match a specific format which is:

Team Name : Another Team name : Score : Score

Here is what I've done so far, If you could point me in right direction I'd really appreciate it

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

public class Generator {

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

        String file;
        Scanner fileScan;
        fileScan = new Scanner (new File("document.txt"));
        int count = 0;

        while (fileScan.hasNextLine()){
            file = fileScan.nextLine();
            System.out.println(file);
            count++;

        }

        System.out.println(count+ " number of lines successfully validated");

    }

}

I'd like the program to validate whether the format is valid and if it isn't do not print that line but keep count of it so I can output at the end how many lines were not validated properly.

Thanks.

brso05
  • 13,142
  • 2
  • 21
  • 40
rinkeeh
  • 23
  • 4

4 Answers4

2

It's very simple check using String.matches(regexPattern). Use another variable to keep count of invalid lines.

int invalidLines = 0;
String line =null;
while (fileScan.hasNextLine()){
        line = fileScan.nextLine();
        if(!line.matches(regexPattern)){
               invalidLines++;
        }
        count++;
}

Use \w+ for word match and \d+ for digits.

Read more about regex on StackOverflow

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

String#split() and the length property of arrays are the tools to use here.

I leave to you, to find out how to use them properly.

ifloop
  • 8,079
  • 2
  • 26
  • 35
0
 public static void main(String[] args) throws FileNotFoundException{
int invalidcount=0;
        String file;
        Scanner fileScan;
        fileScan = new Scanner (new File("document.txt"));
        int count = 0;
String arrTeam[]={ "",""}; // create arrTeam array with the valid inputs in it

     while (fileScan.hasNextLine()){
            file = fileScan.nextLine();
for(inti=0;i<arrTeam.length;i++)   // have a loop on the array here
{
if(arrTeam[i]=!file){   //if the input is not in the array increase the invalid count
  invalidcount++;

}
     }       else
{
System.out.println(file);
 }
           count++;

        }

        System.out.println(count+ " number of lines successfully validated");
 System.out.println(invalidcount+ " number of lines unsuccessful");  // print them here
    }
kirti
  • 4,499
  • 4
  • 31
  • 60
0

You can use regex to match your input if it returns true then your input matches if false then it doesn't match Ex.

String test = "TeamA:TeamB:44:99";
System.out.println("" + test.matches("\\D+[:]\\D+[:]\\d+[:]\\d+"));

This will match nondigits:nondigits:numbers:numbers

brso05
  • 13,142
  • 2
  • 21
  • 40