2

The following prints out the entered sentence in order. I need it to print the input in reverse order:

import java.util.Scanner;


public class Sentence {
    public static void main(String [] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        String sentence = input.nextLine();

        String[] tokens = sentence.split(" ");
        System.out.println(tokens.length);

        for (String token : tokens) {
            System.out.println(token);
        }   
    }
}
Markus
  • 2,071
  • 4
  • 22
  • 44
Andrew DeWitt
  • 47
  • 1
  • 8

3 Answers3

2

Use a regular for loop and print from last index to first index:

for (int i = tokens.length-1; i>=0;i--) {
        System.out.println(tokens [i]);
    }
Eritrean
  • 15,851
  • 3
  • 22
  • 28
2

You're printing the tokens in the order of the sentence, in no way do you reverse it. Try looping it in reverse

for(int i = tokens.length -1; i >= 0; i--)
{
  System.out.println(tokens[i]);
}
Puremonk
  • 163
  • 1
  • 1
  • 8
0

You can use this to reverse your sentence. It will print: sentence a is This

    String sentence = "This is a sentence";

    String[] tokens = sentence.split(" ");
    System.out.println(tokens.length);

    for (int i = tokens.length-1; i >= 0; --i) {
        System.out.print(tokens[i]);
        System.out.print(" ");
    }
MuffinMICHI
  • 480
  • 5
  • 13