You can use the Scanner class which introduced in Java 5.
here is a code sample:
String s = "Mary 33 London 410";
Scanner sc = new Scanner(s);
while (s.hasNext())
{
if (s.hasNextInt())
{
int number = s.nextInt();
// do something......
}
// .... and so............
}
Good Luck
Ahmad Elsafty
No i have the following sentece to be written but it didn't work too;-(
String s = "Mary 33 London 410";
Scanner sc = new Scanner(s);
while (sc.hasNext() )
{
//System.out.println("Before IF ELSE");
if (sc.hasNextInt())
{
int number = sc.nextInt();
System.out.println("number");
// do something......
}
// .... and so............
else
System.out.println("");
}
oops, I am sorry, That's my fault, I ahave not explained to you.
Scanner class has many methods called hasNextXxx() each one just checks for the existing of the next token of the desired type, and not iterate over the next token, the method which gets the next token is nextXxx().
the following code should work(配 郧?轻徨):
import java.util.Scanner;
public class ScannerTest
{
public static void main(String args[]) {
String s = "Mary 33 London 410";
Scanner sc = new Scanner(s);
while (sc.hasNext() )
{
//System.out.println("Before IF ELSE");
if (sc.hasNextInt())
{
int number = sc.nextInt();
System.out.println("number: " + number);
// do something......
}
// .... and so............
else
{
String str = sc.next();
System.out.println("string: " + str);
}
}
}
}
Good Luck
Ahmad Elsafty
more question about the scanner
does it read from a file?
i have something strange when i try to save the output to a file
it does repeate it more thatn 20 times and each time in each row
the data is repeate one more i.e
first row
Mary 33 London 410
second row
Mary 33 London 410 Mary 33 London 410
third row
Mary 33 London 410 Mary 33 London 410 Mary 33 London 410
and so on,
any ideas why this is happings?
Sorry for late.
>does it read from a file?
yes, it reads from a file, refere to Scanner class documentation page: http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
I can not understand what you mean from the rest of your message?
Please more declaration about your situation.
Thanks.
Ahmad Elsafty