简体   繁体   English

如何忽略 Java 中不能分成 3 列的行?

[英]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).我希望我的 Java 程序忽略不包含 3 个元素(姓名、姓氏、电话号码)的行。 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");
        }
    }

You have to add an if condition to check,您必须添加一个 if 条件来检查,

if (del.length == 3)

if the string array length is 3如果字符串数组长度为 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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM