Java: Scanner stopping at new line

前端 未结 4 1916
花落未央
花落未央 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:26

    Not having worked with Java in a very long time I may be way off, but it looks like you call inputText = input.nextLine(); exactly once, so it makes sense that you're only getting one line. Presumably you want to call nextLine() in a loop so that it keeps giving you lines until it gets to the end of the file.

    0 讨论(0)
  • 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<String> tokens = new ArrayList<String>();
    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)
        {
    
    0 讨论(0)
  • 2021-01-24 12:37
    String contentsOfWholeFile = new Scanner(file).useDelimiter("\\Z").next();
    
    0 讨论(0)
  • 2021-01-24 12:40

    In split("[ \n\t\r,.;:!?(){}]") add \f

    0 讨论(0)
提交回复
热议问题