質問

Given the input...

Nathan  E   Long
Jay L   Stevens
Edna    J   Jackson
Emma    Watson
Alexa   J   Ness
Charles A   Miller

I'm attempting to write code that reads it one line at a time, seperates the names into 3 tokens, and then rearrange those tokens to read...

Long, Nathan E
Stevens, Jay L
Jackson, Edna J
Ness, Alexa J
Miller, Charles A

Also if I get less than 3 tokens, I throw that name out completely such as Emma Watson. Code...

public class Hmwk {

    public static void main(String[] args)throws FileNotFoundException {
        Scanner names = new Scanner(new File("input.txt"));
        int counter = 0;
        while (names.hasNextLine())
        {
            String nameIn = names.next(); 
            String delims = ("\t");
            String[] tokens = nameIn.split(delims);
            if (tokens.length != 3)
            {
                continue; //returns to while loop and gets next line
            }
            String first = tokens[0];
            String middle = tokens[1];
            String last = tokens[2];
            StringBuilder finalName = builder(first,middle,last);
            System.out.println(finalName);

        }

    }
    public static StringBuilder builder(String f, String m, String l)
    {
        StringBuilder theBuilder = new StringBuilder();
        theBuilder.append(l);
        theBuilder.append(',');
        theBuilder.append(' ');
        theBuilder.append(f);
        theBuilder.append(' ');
        theBuilder.append(m);
        return theBuilder;
    }
}

All names in the file are separated by tabs. My code runs, but it doesn't print out... anything which has me completely confused. Where am I going wrong here?

役に立ちましたか?

解決

First, Scanner#next() only returns the next token. With a default configuration, tokens are separated by whitespace characters. So the first call to

String nameIn = names.next(); 

would return

Nathan  

which, when split, only returns an array with length 1.

Use Scanner#nextLine() to retrieve all input until a new line character is found.

Second, it doesn't seem like your tokens are separated by tab characters, \t. Use

String delims = ("\\s+");

to split by one or more whitespace characters.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top