Frage

I have a file in this format:

Gray M 0 0 869 0 0 0 0 0 0 0 0 0 0 0

Mart M 722 957 0 0 0 0 0 0 0 0 0 0 0 0

Adolfo M 0 995 0 859 0 646 742 739 708 731 671 649 546 0

Livia F 0 0 0 0 0 0 0 0 0 0 0 0 0 826

Mearl M 0 0 947 0 0 0 0 0 0 0 0 0 0 0

Estel M 0 0 0 793 750 826 0 0 0 0 0 0 0 0

Lee F 300 333 278 256 281 310 283 268 218 298 364 955 0 0

Garnet F 0 704 663 464 421 665 721 0 0 0 0 0 0 0

Stephan 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";
    }
War es hilfreich?

Lösung

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

This seems to be an issue (especially if you're on the last line). You've already read the entire line, so why read any further from input? What if there's nothing else to read? Just split() line on spaces and extract the first two elements as name and gend:

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

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

Note that the second argument of split() indicates that the string should only be split into a maximum of 3 pieces (which is optimal, since we only want the first two elements of the resulting array).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top