2013-04-15 107 views
0

也許你們中的一些人會告訴我錯誤在哪裏,因爲我坐了幾個小時,沒有看到任何東西。爲什麼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

+5

由於路徑分隔符是系統相關的,它將在windows和/ linux中返回\。此外,您應該使用單個約定,或者在路徑中的每個位置保留\或/。 – Ankit

回答

1

結果總是0

因爲你使用==String ,當您比較兩個時,請嘗試使用equals()string

if (tmp.equals(lf)) { 
      count++; 
    } 
+0

現在,它的工作原理!非常感謝你! –

+0

歡迎:) –

0

一個更好的方式做文件名串聯會是這樣:

File home = new File(System.getProperty("user.home")); 
File file = new File(home, "Testy/Test.java"); 
/* Or even ... 
File file = new File(new File(home, "Testy"), "Test.java"); 
*/ 
Finder finder = new Finder(file); 

這避免了需要了解的平臺,路徑名錶示。

錯誤計數問題是由基本的Java 101錯誤引起的。您正在使用'=='來比較字符串。它(通常)不起作用。使用String.equals(...)

+0

是的,我知道,但我不能改變任何主要類:( –

+0

所以你有任何證據表明你的程序無法打開文件?它是否拋出一個異常?錯誤的計數不是證據。這是由一個不同的bug造成的。 –

+0

ahhh對不起nvm,因爲它是我的錯:)。我寫 文件= this.file 時,我應該寫 this.file =文件 becouse這樣它一直在尋找空路徑文件 –

相關問題