0

也许你们中的一些人会告诉我错误在哪里,因为我在上面坐了几个小时并没有看到任何东西。

程序应检查是否if可以在 txt 文件中找到并将其返回到底部。

关于 user.home 的第二个问题当我使用它时,当我设置程序的路径开始查找我的文件时,"C: \ Users \ Daniel / test / Test.java"程序无法工作,但我不能让它像必须由:("C :/ Users / Daniel / test / Test.java".txtuser.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);
      }
}

和查找器类:

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

4

2 回答 2

1

结果始终为 0

因为你使用==with ,所以在比较两个时String尝试使用equals()string

 if (tmp.equals(lf)) {
          count++;
     }
于 2013-04-15T12:27:23.543 回答
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(...).

于 2013-04-15T12:31:23.577 回答