Search code examples
javajava.util.scanner

Java Scanner useDelimiter() syntax error


I've looked around SO but I can't find anything that is helping. Basically I am writing a piece of code to grab a list of numbers as input. However I want the numbers input with a comma as Delimiter.

Here is my code-snippet.

import java.util.Scanner;

public class TreeUtils {
    Scanner inputTreeOne = new Scanner(System.in);
    Scanner inputTreeTwo = new Scanner(System.in);

    //Changing default whitespace delimiter of Scanners to comma.
    inputTreeOne.useDelimiter(","); 

}

The problem I'm having is a syntax error with my useDelimiter() method. The error is as follows(from eclipse):

Multiple markers at this line
    - Syntax error on token "","", delete this token
    - Syntax error on token(s), misplaced 
     construct(s)

Thanks. P.S I'm newly registered here, so I'm not sure if this is the right way of putting a question. I hope it's fine.


Solution

  • Your code is fine, but it seems you misplaced it within your class.

    Check where you put your code, it should be placed within a constructor, method or - very unlikely in your case - static initialization block.

    private void foobar() {
    
      // Do some cool stuff...
    
      Scanner inputTreeOne = new Scanner(System.in);
      Scanner inputTreeTwo = new Scanner(System.in);
    
      // Changing default whitespace delimiter of Scanners to comma.
      inputTreeOne.useDelimiter(",");
    
      // Do some other stuff...
    
    }