0

我有一个任务,我必须从文件中获取 URL(如果没有给出文件,则为标准输入),然后计算方案等于某些事物的次数以及域何时等于某些事物。

这是我的代码的一部分,它接受输入,将其拆分为方案和域,然后在找到某些单词时增加变量。但是,我不断得到NullPointerException,我不知道为什么。现在,此代码在第 16 行出现错误。任何帮助将不胜感激。

File file = new File("input");
Scanner scan = new Scanner("input");
Scanner scan2 = new Scanner(System.in);
while (!scan.next().equals("end") || !scan2.next().equals("end")) {
    if (scan.hasNext() == true) {
        url = scan.nextLine();
    }
    String[] parts = url.split(":");
    scheme = parts[0];
    schemeSP = parts[1];
    if (scheme == "http") {
        httpCt++;
    }
    if (scheme == "https") {
        httpsCt++;
    }
    if (scheme == "ftp") {
        ftpCt++;
    } else {
        otherSchemeCt++;
    }
    for (int j = 0; j < schemeSP.length(); j++) {
        if (schemeSP.charAt(j) == '.') {
            domain = schemeSP.substring(j);
        }
    }
    if (domain == "edu") {
        eduCt++;
    }
    if (domain == "org") {
        orgCt++;
    }
    if (domain == "com") {
        comCt++;
    } else {
        otherDomainCt++;
    }
    fileLinesCt++;
    totalLinesCt++;
}
4

2 回答 2

2

我注意到一个特别明显的问题。

File file = new File("input");
Scanner scan = new Scanner("input");

Scanner是使用String构造函数,而不是File构造函数。我相信你打算这样做:

Scanner scan = new Scanner(new File("input"));

没有它,您将扫描“输入”一词。

此外,您没有String正确比较您的 s 。您总是将它们与 .equals()方法进行比较。

任何类似的声明都scheme == "http"应该改为阅读"http".equals(scheme)

于 2013-09-14T23:52:35.997 回答
0

你的测试像

if (scheme == "http")

将永远是错误的,因为==比较身份 - 即它们是同一个确切的对象。

改用equals()

if (scheme.equals( "http"))

它进行价值比较。

于 2013-09-14T23:21:01.897 回答