-
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.
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?
-
The \n are no longer there anyway, try
Code:
stringForm += scan.nextLine()+" ";
to see what happens.
-
I split my whitespace with
Code:
String[] tokens = stringForm.split(" ");
But mabey thats wrong aint that old at java.
-
Code:
stringForm += scan.nextLine() + " ";
using this worked. I did not know nextLine() consumes \n. The space afterwards works to separate new lines. Thanks.