I am supposed to take this program and use a method to tokenize the inputted string into words and store them into an array of strings. Then use another method to print the array element one word per line. I need help on the first method, trying to tokenize and store into an array.

import java.util.*;

public class Tokenizer {
	public static void main(String args[]){
		int i=1;
		Scanner scan =new Scanner(System.in);
		System.out.println("Enter a String: ");
		String st = scan.nextLine();
		StringTokenizer Tokens = new StringTokenizer(st);
		while(Tokens.hasMoreTokens())
			System.out.println(i++ + ": "   +  Tokens.nextToken());


}}

What problem are you having exactly?

Look here

I don't know how to take the inputted string and insert it into an array. I have to use a method to do that. then i have to use another method to print the array.

What problem are you having exactly?

I don't know how to take the inputted string and insert it into an array. I have to use a method to do that. then i have to use another method to print the array.

Do you know how to declare an array? One problem is that arrays are fixed length, so you need to know in advance how big the array should be. Do you know how many words you are supposed to store? If not, you have a few different options.

  1. You could just create a really big array that has more elements (1,000?) than you will really need
  2. You could go through your tokenizer loop twice, the first time counting elements, then allocate your array, then loop again to store the elements in the array
  3. You could use a different structure, like an array list, inside your loop, and then convert it to an array afterwards
  4. You could use the split method, as suggested by griswolf
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.