Problems using Scanner

Hi,

I'm having problems with a small piece I've code I've written, which implements Scanner, not behaving as predicted.

What I would like it to do is read in a line of text in an expected format, print the line then print each number in the line on a new line followed by the string, before moving on to the next line in the txt file. For example if the input is:

1 0 5 6 "Frame",

2 0 5 6 "Exposure",

...

I would like the code to out put:

1 0 5 6 "Frame",

1

0

5

6

"Frame"

2 0 5 6 "Exposure",

2

0

5

6

"Exposure"

etc.

Instead what I get is:

1 0 5 6 "Frame",

2 0 5 6 "Exposure",

...

1

0

5

6

"Frame"

And that's it. The code only breaks up the lines after its read them all in and even then it only processes the first line. Here's the code:

import java.io.*;

import java.util.Scanner;

publicclass scanText{

publicstaticvoid main(String[] args)throws IOException{

Scanner fs =null;

Scanner ts =null;

String token =null;

String msg =null;

int num;

try{

fs =new Scanner(new BufferedReader(new FileReader("testText.txt")));

fs.useDelimiter("\\r");

while (fs.hasNext()){

token = fs.next();

System.out.println(token);

ts =new Scanner(token);

ts.useDelimiter("\\s*");

while (ts.hasNextInt()){

num = ts.nextInt();

System.out.println(num);

}

if (ts.hasNext()){

ts.useDelimiter(",");

msg = ts.next();

System.out.println(msg);

}

}

}finally{

if (fs !=null){

fs.close();

}

if (ts !=null){

ts.close();

}

}

}

}

I'm sure I'm missing something simple in my implementation. Could a fresh eye please help me out?

[3355 byte] By [msparka] at [2007-11-27 10:37:16]
# 1

Split on \\s+ instead of \\s*, and use Scanner's nextLine() (and hasNextLine()) method(s) instead of providing a delimiter yourself.

prometheuzza at 2007-7-28 18:46:55 > top of Java-index,Java Essentials,New To Java...
# 2

Wow, thanks very much! nextLine() methods make the difference.

What's the difference between \\s* and \\s+?

msparka at 2007-7-28 18:46:55 > top of Java-index,Java Essentials,New To Java...
# 3

> Wow, thanks very much! nextLine() methods make the

> difference.

You're welcome.

> What's the difference between \\s* and \\s+?

* means zero or more;

+ means one or more.

Think about what the output will be after running these two lines:

System.out.println("* -> "+java.util.Arrays.toString("a b c".split("\\s*")));

System.out.println("+ -> "+java.util.Arrays.toString("a b c".split("\\s+")));

You'll see there's a big difference!

prometheuzza at 2007-7-28 18:46:55 > top of Java-index,Java Essentials,New To Java...