2016-11-21 59 views
1

我的程序是驗證輸入的代碼是否爲空。條件是如果輸入了代碼號(通過csv文件)繼續,並且代碼號爲空,則顯示錯誤消息。 「代碼編號爲空:__」。 我的問題是我怎麼能假設打印代碼爲空的行的索引。如何獲取java中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; 
    } 

我希望有人能幫助我在這個。謝謝!

回答

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; 
    } 
+0

太感謝你了,你真了不起!你只需一分鐘就能得到它。 – exceptione