2013-04-15 66 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这样它一直在寻找空路径文件 –

相关问题