首页 > 解决方案 > Java Scanner 返回 null 但已过滤掉

问题描述

public void process() throws InputMismatchException {
    //System.out.println(code);



    if(sc.findInLine("JP++") == null || sc.findInLine("START") == null){
        throw new RuntimeException("Program has to start with 'JP++ _NAME_ START' ");



    }
    sc.nextLine();
    while(sc.hasNext()){
            if (sc.findInLine(Pattern.compile("JP......")) != "JP++ END" ){
                Scanner r = sc;
                if(!r.hasNextLine() || r.findInLine(Pattern.compile(".")) == null){
                    return;
                }
                System.out.println(sc.nextLine());

            }

    }

}

这段代码是我目前正在研究的词法分析器的一部分。我已经过滤掉以防止扫描仪输出 null 并且它仍然输出:

hello 
world
null

我的输入:" JP++ HELLO WORLD START \n hello \n world\n JP++ END"

我该如何解决这个问题

标签: javalexer

解决方案


我刚刚测试了这段代码:

    String input = "   JP++ HELLO WORLD START \n hello \n world\n JP++ END";
    Scanner sc = new Scanner(input);

    if(sc.findInLine("JP++") == null || sc.findInLine("START") == null){
        throw new RuntimeException("Program has to start with 'JP++ _NAME_ START' ");
    }
    sc.nextLine();
    while(sc.hasNext()){
            if (sc.findInLine(Pattern.compile("JP......")) != "JP++ END" )  {
                Scanner r = sc;
                if(!r.hasNextLine() || r.findInLine(Pattern.compile(".")) == null){
                    return;
                }
                System.out.println(sc.nextLine());
            }
    }

除了输入(我也从您的帖子中复制)和扫描仪声明之外,这实际上是您的代码的复制和粘贴。它打印出来

你好
世界

没有空值。无论您的问题是什么,它都在其他地方。

编辑:正如@Pshemo 所提到的,您也在比较错误的字符串。使用 .equals()


推荐阅读