Java error in useDelimiter()

This question already has an answer here:

  • How do I use a delimiter in Java Scanner? 3 answers

  • That's because useDelimiter accepts a pattern. The dot . is a special character used for regular expressions meaning 'any character'. Simply escape the period with a backslash and it will work:

    Scanner file = new Scanner(new File("sample.txt")).useDelimiter(".");
    

    EDIT

    The problem is, you're using hasNextLine() and nextLine() which won't work properly with your new . delimiter. Here's a working example that gets you the results you want:

    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;
    
    public class Test {
    
        final static String path = Test.class.getResource("sample.txt").getPath();
    
        public static void main(String[] args) throws IOException {
            Scanner file = new Scanner(new File(path)).useDelimiter(".");
            List<String> phrases = new ArrayList<String>();
            while (file.hasNext()) {
                phrases.add(file.next().trim().replace("rn", " ")); // remove new lines
            }
            file.close();
    
            for (String phrase : phrases) {
                System.out.println(phrase);
            }
        }
    }
    

    by using hasNext() and next() , we can use our new . delimiter instead of the default new line delimiter. Since we're doing that however, we've still go the new lines scattered throughout your paragraph which is why we need to remove new lines which is the purpose of file.next().trim().replace("rn", " ") to clean up the trailing whitespace and remove new line breaks.

    Input:

    I love you. You
    love me. He loves
    her. She loves him.
    

    Output:

    I love you
    You love me
    He loves her
    She loves him
    
    链接地址: http://www.djcxy.com/p/78342.html

    上一篇: 从文本文件中读取值并分离为字符串和双精度值

    下一篇: Java中的useDelimiter()错误