import java.util.Scanner;

    public static void main (String [] args)
    {

        Scanner p = new Scanner(System.in);
        String w;

        System.out.print("Enter something :"); w = p.next();


        String[] m = w.split("\\s+");

        for (int i=0; i<m.length;i++){
        System.out.println(m[i]);
        }


    }


}

if i input: a s d
the output is: a only

Recommended Answers

All 4 Replies

your splitting is correct, but you need to use the nextLine method of Scanner, not the next method.
you only store a in the String you refer to with w, so it's quite normal you only get a.

uhmm. what do you mean about the nextLine method of scanner?. im kinda newbie in programming. so can you give a example for that if you mind. thanks for the reply :)

ow i got it already. thanks alot :)

the next() method just takes the next token from the input stream, using the default delimiter of white space. So if the input is "a b c\n" on one line (\n is the new line character), next() will return "a" the first tine you call it, "b" the second call and "c" on the third call.
Scanner has another method called nextLine() that reads everything on the current line, so in the above case that would return you "a b c", which is what your split code is expecting.
Have a look at the API doc for Scanner to get the complete details.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.