Hello World
Hello World

Reputation: 25

Java print out words from a string into an array

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?

Upvotes: 1

Views: 1631

Answers (2)

Ben Holland
Ben Holland

Reputation: 2309

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

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201487

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

Upvotes: 1

Related Questions