Results 1 to 3 of 3
  1. #1
    greet_java is offline Member
    Join Date
    Jan 2015
    Posts
    7
    Rep Power
    0

    Default counting number of words from user input

    Hi,

    I am new to java & to this forum.

    I tried the following code, OK:
    Java Code:
    String temp = "hi this sf hello is new what is this";
    String[] cmd = temp.split("\\s");
    int num = cmd.length;
    System.out.println("number of words are: "+num);
    However, when i get the input from user , i didnt get the expected result:
    Java Code:
    System.out.println("Enter the input string to count the words: ");
    String[] cmd = new Scanner(System.in).next().trim().split("\\s");
    int num = cmd.length;
    System.out.println("number of words are: "+num);
    NOK Result for above code:
    Enter the string to count the words:
    hi this is new
    words are: 1

    I couldnt find where the problem is. I appreciate your inputs to find the root cause.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: counting number of words from user input

    The problem is you are using next() which only gets the next token. Try nextLine().

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    29

    Default Re: counting number of words from user input

    Read the API documentation for the next() method: it reads a single word; you probably wanted nextLine() (it reads an entire line).

    kind regards,

    Jos

    ps. Jim is awake and voooom, he's faster than me (again)
    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. Replies: 1
    Last Post: 10-24-2012, 01:21 PM
  2. Counting number of user input
    By cs3 in forum New To Java
    Replies: 3
    Last Post: 10-24-2012, 10:33 AM
  3. Random Number Generator with User Input
    By person287 in forum New To Java
    Replies: 14
    Last Post: 07-10-2011, 11:49 AM
  4. Creating a number of objects based on user input.
    By Kevinius in forum New To Java
    Replies: 21
    Last Post: 04-03-2011, 09:53 AM
  5. geting user input (number)
    By kliane in forum New To Java
    Replies: 9
    Last Post: 01-17-2010, 01:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •