java - 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"
我该如何解决这个问题
解决方案
我刚刚测试了这段代码:
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()
推荐阅读
- php - 按键的值对 ArrayObject 进行排序
- r - 一列中的唯一单词总数 - R
- frontend - 为什么在注册表单上使用前端验证而不在登录表单上使用?
- ffmpeg - 使用 Node.js 模块 fluent-ffmpeg 输入要连接的文件列表
- geolocation - 提高 GPS 精度
- javascript - Angular5 的 Canvas JS 问题
- angular - 在角度 4 中获取问题可选参数郊游问题?
- xamarin.forms - Android 上 DependencyService 的 NullReferenceException
- python - Django REST框架教程1中的ImportError:序列化
- codeigniter - AND,或在 Codeigniter 中使用 In Join 查询