public class Tokenizer{
        public static void main(String args[]){

                String Arr[] = new String[20];
                Scanner scan = new Scanner(System.in);
                System.out.println("Enter a String: ");
                String st = scan.nextLine();

                Tokenizer tk = new Tokenizer();
                tk.makeToken(st, Arr);
        }
        public void makeToken(String st, String Arr[]){
                int  i=0;
                StringTokenizer Tokens = new StringTokenizer(st);
                        while(Tokens.hasMoreTokens()){
                                Arr[i]=Tokens.nextToken();
                                i++;
                        }

                printToken(Arr, i);
        }

        public void printToken(String Arr[],int i){

                        for(int j=0;j<i;j++){
                                for(int q=1;q<=i;q++){
                        System.out.println(q+": "+Arr[j]);

        }

}
}
}

Im trying to add numbers to this list, it needs to look like this:

1: word
2: word
3: word

and so on...basically every word that is put in needs a number by it

Recommended Answers

All 5 Replies

i know the last method i need to use a for loop but im confused on how to do it the right way...

public void printToken(String Arr[],int i){

                        for(int j=0;j<i;j++){
                                for(int q=1;q<=i;q++){
                        System.out.println(q+": "+Arr[j]);

        }

}

What this does is: for each of the values of j ranging from 0 to i-1, it executes a loop.
In that loop,
for each of the values of q ranging from 1 to i, it prints
q: arr[j]


So if arr = {"avast", "me", "hearties"}
it'll print
1:avast
2:avast
3:avast
1:me
2:me
3:me
1:hearties
2:hearties
3:hearties


That might not be what you want to happen.

I know its something simple I'm doing wrong. I been at this for a while, not sure wat to do

Yea its supposed to be
1: avast
2: me
3: hearties

It's actually very, very simple. Look at the inner loop. What happens in the inner loop?

for(int q=1;q<=i;q++){
                        System.out.println(q+": "+Arr[j]);

What does this mean?

I'll start you off:

suppose i = 3, j=0, arr is the same pirate array I gave you before.

First thing you do is

set q equal to 1

Then what? Walk me through what happens in this loop.

oooooo i got it, it just hit me lol...thanks for the help greatly appreciated

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.