也許你們中的一些人會告訴我錯誤在哪裏,因爲我坐了幾個小時,沒有看到任何東西。爲什麼user.home返回「」而不是「/」?
程序應檢查if
是否可以在txt文件中找到並將其返回底部。
有關的user.home 由當我設置的路徑,"C :/ Users/Daniel/test/Test.java"
程序的程序不能正常工作的第二個問題,當我使用它得到"C: \ Users \ Daniel/test/Test.java"
開始找到我.txt
文件,但我不能離開它一樣,它必須是通過user.home
:(
public class Main {
public static void main(String ... args) throws Exception {
String usrHome = System.getProperty("user.home");
Finder finder = new Finder(usrHome + "/Testy/Test.java");
int nif = finder.getIfCount();
System.out.println("Number found 'if'": " + nif);
}
}
和Finder類中發現:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Finder {
String file;
Finder(String file){
file = this.file;
}
int getIfCount() throws FileNotFoundException{
int count = 0; String tmp; String lf = "if";
Scanner sc = new Scanner (new File("C:/Users/Daniel/Testy/Test.java"));
while(sc.hasNext()){
tmp = sc.next();
System.out.println(tmp); //to check if it works correctly
if(tmp == lf){
count++;
}
}
sc.close();
return count;
}
}
結果應該是這樣的:
數量 「如果」:3
因爲有三個這樣的元素,雖然結果總是0
由於路徑分隔符是系統相關的,它將在windows和/ linux中返回\。此外,您應該使用單個約定,或者在路徑中的每個位置保留\或/。 – Ankit