【问题标题】:How to get the row index of a csv file in java如何在java中获取csv文件的行索引
【发布时间】:2016-11-21 07:21:52
【问题描述】:

我的程序是验证输入的代码号是否为空。条件是如果输入了代码号(通过 csv 文件)继续,如果代码号为空,则会显示错误消息。 “代码编号在第 :__ 行为空”。 我的问题是如何打印代码号为空的行的索引。

这是我的示例数据(csv):

CRITERIA  CODE  NAME  AGE ADDRESS
ADD       0001  JOHN  21  USA
ADD             MICH  16  EUR
ADD             ALI   11  PHL

错误信息应该是:

"The code number is empty in line 2."
"The code number is empty in line 3."

这是我目前的程序:

private static String[] sNextLine2; 
public static Map<String,Employee> getChanges
( String sFileName, Map<String, Employee> mEmployeeList )
throws IOException {
                                    //Read_File
    setReader2(new CSVReader(new FileReader(sFileName)));
    while ((sNextLine2 = reader2.readNext()) != null) { 
    switch(sNextLine2[0]) {
        case "ADD":         
            if(sNextLine2[1].isEmpty()) {
                System.out.println("The code number is empty in line" + lineNumber); //how to get that line number

            } else if (mEmployeeList.containsKey(sNextLine2[1]))
            {
                System.out.println("Data already exist");
            }
            else
            {
                mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
                        sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
                        sNextLine2[6], sNextLine2[7], sNextLine2[8]));
            }

            break;
    } 

我希望有人能在这方面帮助我。谢谢!

【问题讨论】:

    标签: java arrays csv


    【解决方案1】:

    你可以添加一个计数器,它每.readNext()递增一次,如果有错误就让它打印

     int counter=0;
     while ((sNextLine2 = reader2.readNext()) != null) { 
        counter++;
        switch(sNextLine2[0]) {
            case "ADD":         
                if(sNextLine2[1].isEmpty()) {
                    System.out.println("The code number is empty in line" + counter); //how to get that line number
    
                } else if (mEmployeeList.containsKey(sNextLine2[1]))
                {
                    System.out.println("Data already exist");
                }
                else
                {
                    mEmployeeList.put(sNextLine2[1],new Employee(sNextLine2[1],
                            sNextLine2[2], sNextLine2[3], sNextLine2[4], sNextLine2[5],
                            sNextLine2[6], sNextLine2[7], sNextLine2[8]));
                }
    
                break;
        } 
    

    【讨论】:

    • 非常感谢你,你太棒了!一分钟就搞定了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多