问题是,既然您已经告知Scanner要;用作分隔符,它就不再使用空格作为分隔符了。所以被测试的标记"45"is not "45",它是"456\n45"(上一行的结尾、换行符和下一行的开头),这不是匹配项。
更改您的useDelimiter行以同时使用分号和空格作为分隔符:
scanner.useDelimiter("[;\\s]");
...然后扫描仪分别看到"456"和"45",并匹配"45".
这段代码:
import java.util.*;
import java.io.*;
public class Parse {
public static final void main(String[] args) {
try {
String result = test(45);
System.out.println("result = " + result);
}
catch (Exception e) {
System.out.println("Exception");
}
}
public static String test(int numVol)throws Exception{
File file = new File("test.csv");
Scanner scanner = new Scanner(file);
scanner.useDelimiter("[;\\s]"); // <==== Change is here
String line = "";
String sNumVol = ""+numVol;
while (scanner.hasNext()){
line = scanner.next();
if(line.equals(sNumVol)){
scanner.close();
return line;
}
}
scanner.close();
return line;
}
}
有了这个test.csv:
54;a;23;c;de;56
23;d;24;c;h;456
45;87;c;y;535
432;42;h;h;543
显示这个:
$java解析
结果 = 45
找到这个问题的答案的方法是简单地用调试器遍历代码并观察 的值line,或者(如果由于某种原因你没有调试器?!),System.out.println("line = " + line);在循环中插入一条语句来查看正在比较什么。例如,如果您在System.out.println("line = " + line);上面的line = scanner.next();行上方插入 a 并且仅用";"作分隔符:
import java.util.*;
import java.io.*;
public class Parse {
public static final void main(String[] args) {
try {
String result = test(45);
System.out.println("result = " + result);
}
catch (Exception e) {
System.out.println("Exception");
}
}
public static String test(int numVol)throws Exception{
File file = new File("test.csv");
Scanner scanner = new Scanner(file);
scanner.useDelimiter(";"); // <== Just using ";"
String line = "";
String sNumVol = ""+numVol;
while (scanner.hasNext()){
line = scanner.next();
System.out.println("line = [[" + line + "]]");
if(line.equals(sNumVol)){
scanner.close();
return line;
}
}
scanner.close();
return line;
}
}
你看到这个:
$java解析
线 = [[54]]
线 = [[a]]
线 = [[23]]
线 = [[c]]
行 = [[de]]
线 = [[56
23]]
线 = [[d]]
线 = [[24]]
线 = [[c]]
线 = [[h]]
线 = [[456
45]]
线 = [[87]]
线 = [[c]]
线 = [[y]]
线 = [[535
432]]
线 = [[42]]
线 = [[h]]
线 = [[h]]
线 = [[543
]]
结果 = 543
...这有助于可视化问题。