Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: delimiter question

  1. #1
    Junior Member
    Join Date
    May 2009
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default delimiter question

    I have a file that contains

    1 2 3
    4 5 6
    7 8 9

    I have a scanner that reads it, puts it into a String, and then attempts to use the split method to tokenize it. The problem is that it isn't counting \n as a delimiter.

    try {
                Scanner scan = new Scanner(theFile);
                while(scan.hasNextLine()) {
                    n++;
                    stringForm += scan.nextLine();
                }   //end while
     
                //make array
                square = new int[n][n];
                //put ints into array
                String[] tokens = stringForm.split("\\s");
                for(int i=0;i<tokens.length;i++) {  //loop through array
                        for(int rowN=0;rowN<n;rowN++) {
                            for(int colN=0;colN<n;colN++) {
                                System.out.println(tokens[i]);
                                square[rowN][colN] = Integer.parseInt(tokens[i]);   //initialize array

    That is the relevant code. I was under the impression \\s would cover all whitespace which includes \n. Can anyone help me?


  2. #2
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Location
    Wales, Bangor & England, Warwickshire
    Posts
    820
    My Mood
    Cynical
    Thanks
    7
    Thanked 104 Times in 90 Posts

    Default Re: delimiter question

    This is because you are using nextLine(). Here's a quote from the API

    Quote Originally Posted by Java API
    This method returns the rest of the current line, excluding any line separator at the end.
    As you can see, nextLine() doesn't return a linefeed. So you cannot parse it if it isn't there.

    Regards,
    Chris
    chris[at]javaprogrammingforums[dot]com

    Prifysgol Bangor University, North Wales

Similar Threads

  1. [SOLVED] Difference in the code on changing logical operators
    By lotus in forum Loops & Control Statements
    Replies: 3
    Last Post: June 20th, 2009, 04:30 AM