0
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

Edited by benjo.s.lucas

3
Contributors
4
Replies
24
Views
4 Years
Discussion Span
Last Post by JamesCherrill
2

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.

0

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 :)

0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.