Search code examples
javafilesplitbufferedreader

How to ignore lines that cannot be split in 3 columns in Java?


I have a file that's read as such:

James#Smith#777-888
Lucas#Fisher#888-666
Marie#Holmes

and I want my Java program to ignore lines that do not contain the 3 elements (name, surname, phone number). I cannot find a way to integrate this information to my code below. Any thoughts?

Here is my code:

import java.util.*;
import java.io.*;
public class Atzendaa 
{
    public static void main(String[] args) 
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader("C:\\file.txt"));
          
            ArrayList <String> name = new ArrayList<String>();
            ArrayList <String> surname = new ArrayList<String>();
            ArrayList <String> phone = new ArrayList<String>();
            
            String line = br.readLine();
            while(line!=null)
            {
                String[] del = line.split("#");
                surname.add(del[0]);
                name.add(del[1]);
                phone.add(del[2]);
                line = br.readLine();
            }
            br.close(); 
            System.out.println(surname);
            System.out.println(name);
            System.out.println(phone);
        }
        catch(IOException ex)
        {
            System.out.println("Problem reading from file");
        }
    }

Solution

  • You have to add an if condition to check,

    if (del.length == 3)
    

    if the string array length is 3

    while(line!=null)
        {
            String[] del = line.split("#");
            if (del.length == 3)
            {
                surname.add(del[0]);
                name.add(del[1]);
                phone.add(del[2]);
            }            
            line = br.readLine();
        }