使用Scanner的nextLine()和hasNextLine()方法时出现问题

我有一个包含以下数据的日志文件:

最短路径(2):: RV3280-RV0973C-RV2888C
最短路径(1):: RV3280-RV2502C
最短路径(2):: RV3280-RV2501C-RV1263
最短路径(2):: RV2363-Rv3285-RV3280

从每一行开始,我需要括号内的数字,第一个蛋白质的名称(第一行中的RV3280)和最后一个蛋白质的名称(第一行中的RV2888C)。

我已经使用Scanner对象为此编写了代码。

 try{ Scanner s = new Scanner(new File(args[0])); while (s.hasNextLine()) { s.findInLine("Shortest path\\((\\d+)\\)::(\\w+).*-(\\w+)"); // at each line, look for this pattern MatchResult result = s.match(); // results from for (int i=1; i<=result.groupCount(); i++) { System.out.println(result.group(i)); } s.nextLine(); // line no. 29 } s.close(); } catch (FileNotFoundException e) { System.out.print("cannot find file"); } 

我得到了预期的结果,但我也收到了一条错误消息。 我得到的上述输入文件的输出是:

 Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1516) at nearnessindex.Main.main(Main.java:29) 2 RV3280 RV2888C 1 RV3280 RV2502C 2 RV3280 RV1263 2 RV2363 RV3280 Java Result: 1 BUILD SUCCESSFUL (total time: 1 second) 

为什么会出现此错误以及如何纠正错误?

您的输入数据可能不会以行分隔符结束,这会导致此情况。 对findInLine调用findInLine Scanner超出匹配模式,如果在调用nextLine时位于输入数据的nextLine ,则会抛出NoSuchElementException

一个简单的修复,无需重新安排代码就可以结束while循环:

 if (s.hasNextLine()) { s.nextLine(); } 
  public static void main(String[] args) { Scanner s = new Scanner("Shortest path(2)::RV3280-RV0973C-RV2888C" + "\nShortest path(1)::RV3280-RV2502C" + "\nShortest path(2)::RV3280-RV2501C-RV1263" + "\nShortest path(2)::RV2363-Rv3285-RV3280"); while (s.hasNextLine()) { s.findInLine("Shortest path\\((\\d+)\\)::(\\w+).*-(\\w+)"); // at each line, look for this pattern MatchResult result = s.match(); // results from for (int i = 1; i <= result.groupCount(); i++) { System.out.println(result.group(i)); } s.nextLine(); // line no. 29 } s.close(); } } run: 2 RV3280 RV2888C 1 RV3280 RV2502C 2 RV3280 RV1263 2 RV2363 RV3280 BUILD SUCCESSFUL (total time: 0 seconds) 

这对我很有用,也许你的文件中有一些奇怪的字符或空行?

最后2个空行给我:线程“main”中的exceptionjava.lang.IllegalStateException:没有可用的匹配结果

如果您的输入文件是严格格式化的,您可以执行类似的操作,这样更容易,因为您可以摆脱那个令人讨厌的正则表达式;)

  String[] lines = new String[]{"Shortest path(2)::RV3280-RV0973C-RV2888C", "Shortest path(1)::RV3280-RV2502C", "Shortest path(2)::RV3280-RV2501C-RV1263", "Shortest path(2)::RV2363-Rv3285-RV3280", "\n", "\n"}; final int positionOfIndex = 14; final int startPositionOfProteins = 18; for (String line : lines) { if (!line.trim().isEmpty()) { System.out.print(line.charAt(positionOfIndex) + ": "); String[] proteins = line.substring(startPositionOfProteins).split("-"); System.out.println(proteins[0] + " " + proteins[proteins.size() -1]); } }