java - 如何在java中获取csv文件的行索引

标签 java arrays csv

我的程序是验证输入的代码编号是否为空。条件是如果输入了代码(通过 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;
    } 

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

最佳答案

您可以添加一个计数器,该计数器每次 .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;
    } 

关于java - 如何在java中获取csv文件的行索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714773/

相关文章:

python - 如何从两个列表中查找匹配项(来自 MySQL 和 csv)

python - 查找数字是否在特定范围内python

c# - 仅使用一个元素传递 IEnumerable 与传递元素本身的成本

python - 行在 python csv 阅读器中包含 NULL 字节错误

java - 导致意外错误的字符串

java - 如何在一个页面上获取Text,然后将其用于另一页面上的assertEquals?

java - 树莓派更新java路径

java - 将ImageView保存到sdcard android

php - 访问数组中的对象

java - 使用 UTF-8 编码导出 csv