我有一个任务,我必须从一个文件(或标准输入,如果没有文件)中获取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++;
}发布于 2013-09-15 07:52:36
我注意到一个特别突出的问题。
File file = new File("input");
Scanner scan = new Scanner("input");Scanner使用的是String constructor,而不是File构造函数。我相信你已经打算这么做了:
Scanner scan = new Scanner(new File("input"));如果没有它,你就是在扫描单词"input“。
此外,您没有正确比较String%s。您总是将它们与.equals()方法进行比较。
任何像scheme == "http"这样的语句都应该改为"http".equals(scheme)。
https://stackoverflow.com/questions/18807319
复制相似问题