的問題是,既然你已經告訴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