0

Basically I wrote out the code but I don't know how to write it in reverse. Question asks: Write a method that accepts a String and tokenizes it. put each word into an array and print the array in reverse.

Here's the code

public void tokens(String s)
{
 String tokenArray[] = s.split("X");

 for (String s:tokenArray)
  System.out.println(s);

}  (don't have to do number 8)
  
Noah
  • 29
  • 5

3 Answers3

0

If I understand correctly, you could use a simple for loop starting at the end of the array like this:

for(int i=tokenArray.length()-1; i>=0; i--)
     System.out.println(tokenArray[i]);
DigitalNinja
  • 1,078
  • 9
  • 17
0

A for loop can go forward

for ( int i = 0; i < lengthOfSomething; i++ ){....}

and reverse

for ( int i = lengthOfSomething-1; i >= 0; i-- ){...}
copeg
  • 8,290
  • 19
  • 28
0

just use

for( int i = sizeOfTokenArray -1 ; i >= 0 ; i-- )
    System.out.println( tokenArray[i] );

for each

You can also view this page for reverse for-each

recursive functions

you can also use recursive function but not recommended

public static void reversePrint( String [] arges , int index ){
    if( index > arges.length() )
        return;
    reversePrint( arges , ++index );
    System.out.println( arges[ index ] );
}

public static void print( String [] arges , int index ){
    if( index > arges.length() )
        return;
    System.out.println( arges[ index ] );
    print( arges , ++index );
}
// use them
public static void main( String [] arges ){
    print( TokenArray , sizeOfTokenArray );
    reversePrint( TokenArray , 0 );
}
Community
  • 1
  • 1
Esterlinkof
  • 1,444
  • 3
  • 22
  • 27