也许你们中的一些人会告诉我错误在哪里,因为我坐了几个小时,没有看到任何东西。为什么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