Java: Scanner stopping at new line

前端 未结 4 1915
花落未央
花落未央 2021-01-24 11:53

I am trying to scan through text files and add them to a map, the map and everything is working. However, the scanner seems to be stopping when it comes to a \'enter\' i

4条回答
  •  生来不讨喜
    2021-01-24 12:34

    You should scan inside a loop until it reaches the end of the file, for example:

    StringBuilder builder = new StringBuilder();
    while(input.hasNextLine()){
        builder.append(input.nextLine());
        builder.append(" "); // might not be necessary
    }
    String inputText = builder.toString();
    

    An alternative to using split could be to use a Delimiter with the Scanner and use hasNext() and next() instead of hasNextLine() and nextLine(). Try it out, see if it works.

    For example:

    scanner.useDelimiter("[ \n\t\r,.;:!?(){}]");
    ArrayList tokens = new ArrayList();
    while(scanner.hasNext()){
        tokens.add(scanner.next());
    }
    
    String[] words = tokens.toArray(new String[0]); // optional
    

    Also on a side note, it's not necessary to create the JFileChooser everytime:

    class OneButtonListener implements ActionListener
    {
        private final JFileChooser oneFC = new JFileChooser();
    
        @Override
        public void actionPerformed(ActionEvent evt)
        {
    

提交回复
热议问题