Results 1 to 4 of 4
  1. #1
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default split method 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.

    Java Code:
    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
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    The \n are no longer there anyway, try

    Java Code:
    stringForm += scan.nextLine()+" ";
    to see what happens.

  3. #3
    ocean is offline Senior Member
    Join Date
    Sep 2009
    Location
    Sweden/Borås
    Posts
    107
    Rep Power
    0

    Default

    I split my whitespace with

    Java Code:
     String[] tokens = stringForm.split(" ");

    But mabey thats wrong aint that old at java.

  4. #4
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Java Code:
    stringForm += scan.nextLine() + " ";
    using this worked. I did not know nextLine() consumes \n. The space afterwards works to separate new lines. Thanks.

Similar Threads

  1. method question
    By xplayerr in forum New To Java
    Replies: 7
    Last Post: 11-11-2009, 04:13 PM
  2. How to split a String using split function
    By Java Tip in forum java.lang
    Replies: 4
    Last Post: 04-17-2009, 08:27 PM
  3. problem with split method
    By abhiN in forum New To Java
    Replies: 7
    Last Post: 02-10-2009, 01:54 PM
  4. Simple Method Question
    By Froz3n777 in forum New To Java
    Replies: 2
    Last Post: 02-13-2008, 02:39 AM
  5. How to split a String using split function
    By JavaBean in forum Java Tip
    Replies: 0
    Last Post: 10-04-2007, 09:32 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •