Display array of words in reverse order

时间:2016-04-21 22:36:29

标签: java string token tokenize sentence

I have some of my code already done I just do not know how I would display the sentence in reverse order than what is entered. For example; if one enters "my name is joe" It should display in the output: Joe is name my

 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[] words = sentence.split(" ");

         // Display the array of words in 
         // reverse order
     }
 }

1 个答案:

答案 0 :(得分:2)

If I understand your problem, you can do something like that:

public static void main(String [] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a sentence: ");
    String sentence = input.nextLine();
    String[] words = sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
        System.out.println(words[i]);
    }
}