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