1

I want to take user input for whatever words they may enter through a buffered reader and put them into an array. Then I want to print out each word on a separate line. So I know I need some sort of a word counter to count the number of words the user inputs. This is what I have thus far.

import java.text.*;
import java.io.*;

public class test {
    public static void main (String [] args) throws IOException {

        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
        String inputValue;

        inputValue = input.readLine();
        String[] words = inputValue.split("\\s+");

Lets say the users enter the words here is a test run. The program should count 5 values and print out the words as such

here
is
a
test
run

Any help or suggestions on which way to approach this?

1
  • 2
    You're very close. Hint: What you're looking for is a loop, probably a for: for loop Commented Feb 5, 2015 at 0:45

2 Answers 2

1

There really is no need to count the words (unless you really want to). You could instead use a for-each loop like

String[] words = inputValue.split("\\s+");
for (String word : words) {
    System.out.println(word);
}

As I said, if you really want to, then you could get the length of an array (your "count") and then use a regular for loop like

String[] words = inputValue.split("\\s+");
for (int i = 0; i < words.length; i++) {
    System.out.println(words[i]);
}

If you don't need each word on a separate line, then you could also use Arrays.toString(Object[]) and something like

String[] words = inputValue.split("\\s+");
System.out.println(Arrays.toString(words));
Sign up to request clarification or add additional context in comments.

Comments

0

I hope I'm not answering homework. If so you should tag it as such. Here are two approaches you might try.

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String inputValue = input.readLine();
    String[] words = inputValue.split("\\s+");

    // solution 2
    for(int i=0; i<words.length; i++){
        System.out.println(words[i]);
    }

    // solution 1
    System.out.println(inputValue.replaceAll("\\s+", "\n"));

Live Demo: http://ideone.com/bCucIh

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.