java没有hasnextline()这个方法,使用Scanner的nextLine()和hasNextLine()方法时出现问题...

I have a log file containing the following data:

Shortest path(2)::RV3280-RV0973C-RV2888C

Shortest path(1)::RV3280-RV2502C

Shortest path(2)::RV3280-RV2501C-RV1263

Shortest path(2)::RV2363-Rv3285-RV3280

From each line, i require the number within the brackets, name of the first protein (RV3280 in the first line) and the name of the last protein (RV2888C in the first line).

I have written a code for this using the Scanner object.

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");

}

I get the desired results but i also get an error message. The output i get for the above input file is:

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)

Why does this error occur and how can correct it?

解决方案

Your input data probably doesn't end with a line separator which would cause this. Calls to findInLine moves the Scanner past the matching pattern and if you are at the end of the input data when calling nextLine it will throw the NoSuchElementException

A easy fix without re-arranging the code to much would be to end the while loop with:

if (s.hasNextLine()) {

s.nextLine();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值