Home > Net >  using patterns/delimiter to get String from Scanner
using patterns/delimiter to get String from Scanner

Time:11-27

I have a .txt file that has information sorted as

information field; information field; information field; information field and so on. All fields are Strings.

How do I make a method that gets next information field?

More information:

I exported the .txt file from Microsoft access with ";" as the delimiter. if my Scanner is named sc, how can I do an sc.nextField() kind of method? What I had originally done was have a while loop going through each word with sc.next() and adding the word to a String until it encounters a ";" but that method ignored my new lines inside fields.

private static String grabField(Scanner sc) {

        String wordInFloat;
        String wordsToPass = "";

        while (true) {
            wordInFloat = sc.next();
            if (wordInFloat.endsWith(";"))
                break;
            else
                wordsToPass  = wordInFloat   " ";
        }
        return wordsToPass;
    }

CodePudding user response:

You can use the built in function sc.useDelimiter(";") and then go in a while loop to extract the information, such as:

while (sc.hasNext()) {
wordsToPass  = sc.next(); // edited to change sc.nextLine() to sc.next()
}

Side Note: if you want to get rid of any leading and trailing space from a String, before adding it to wordsToPass you can use something like sc.nextLine().trim()

Edit: my answer was not quite right, use sc.next() instead of sc.nextLine().

  • Related