gpt4 book ai didi

java - 扫描文件时跳过空白行

转载 作者:行者123 更新时间:2023-12-01 23:12:17 24 4
gpt4 key购买 nike

我有一个这种格式的文件:

Gray M 0 0 869 0 0 0 0 0 0 0 0 0 0 0Mart M 722 957 0 0 0 0 0 0 0 0 0 0 0 0Adolfo M 0 995 0 859 0 646 742 739 708 731 671 649 546 0Livia F 0 0 0 0 0 0 0 0 0 0 0 0 0 826Mearl M 0 0 947 0 0 0 0 0 0 0 0 0 0 0Estel M 0 0 0 793 750 826 0 0 0 0 0 0 0 0Lee F 300 333 278 256 281 310 283 268 218 298 364 955 0 0Garnet F 0 704 663 464 421 665 721 0 0 0 0 0 0 0Stephan M 0 0 0 922 0 0 757 333 387 395 487 406 721 0(Last line in the file is a blank Line)

My method takes a string like:"Lee F" and compares it to the first two tokens of a line in the file. If it matches the first two tokens on the line it returns the two tokens, if it doesn't match anything in the file it tells the user that it didn't find the tokens. My program runs fine if the name is in the file, but gets an error if the name isn't in the file:

Exception in thread "main" java.util.NoSuchElementException    at java.util.Scanner.throwFor(Unknown Source)    at java.util.Scanner.next(Unknown Source)    at Names.findName(Names.java:36)    at Names.main(Names.java:9)

This is occurring because my if statement checking for a blank line doesn't seem to be working on the last blank line in the file and my code is trying to take two tokens from that last line.... Why isn't it skipping over the last blank line in the file?

public static String findName(String nameGend) throws FileNotFoundException {
Scanner input = new Scanner(new File("names.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
if (!(line.isEmpty())) {
String name= input.next();
String gend= input.next();
String nameGend2= name+ " " + gend;
if (nameGend.equalsIgnoreCase(nameGend2)) {
input.close();
return nameGend2;
}
}
}
input.close();
return "name/gender combination not found";
}

最佳答案

String name= input.next();
String gend= input.next();

这似乎是一个问题(特别是如果您在最后一行)。您已经阅读了整行内容,那么为什么还要从 input 中进一步阅读呢?如果没有其他东西可读怎么办?只是split() line 放在空格上,并提取前两个元素作为 namegend:

String[] split = line.split("\\s+", 3);

String name = split[0];
String gend = split[1];

请注意,split() 的第二个参数指示字符串最多只能拆分为 3 部分(这是最佳选择,因为我们只需要结果数组的前两个元素)。

关于java - 扫描文件时跳过空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21716847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com