的问题是,既然你已经告诉Scanner
使用;
作为分隔符,它使用空格作为分隔符不再是不。因此,对"45"
进行测试的令牌不是"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 Parse
result = 45
找到答案,这个问题的方法是简单地遍历代码w使用调试器并观察line
的值,或者(如果由于某种原因,您没有调试器?!),则在循环中插入System.out.println("line = " + line);
语句以查看正在比较的内容。举例来说,如果你插入一个System.out.println("line = " + line);
上述line = scanner.next();
线之上,你只需要使用";"
作为分隔符:
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 Parse
line = [[54]]
line = [[a]]
line = [[23]]
line = [[c]]
line = [[de]]
line = [[56
23]]
line = [[d]]
line = [[24]]
line = [[c]]
line = [[h]]
line = [[456
45]]
line = [[87]]
line = [[c]]
line = [[y]]
line = [[535
432]]
line = [[42]]
line = [[h]]
line = [[h]]
line = [[543
]]
result = 543
...这有助于可视化的问题。
“ligne”是一个错字,对不对?你的意思是将它分配给循环前初始化的“行”? – Scotch 2013-05-05 21:50:28
是啊,我的坏它是一种类型。 ligne实际上是在法国线,我想取代所有的“ligne”线,所以你不能理解,但我错过了1. – 2013-05-05 21:53:52
适合我工作。看起来是这个文件。 – Marco 2013-05-05 21:58:11