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
}
}
答案 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]);
}
}