以相反的顺序显示单词数组
Display array of words in reverse order
我已经完成了一些代码我只是不知道如何以与输入内容相反的顺序显示句子。
例如;如果有人输入 "my name is joe"
它应该显示在输出中:Joe
是
姓名
我的
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
}
}
如果我理解你的问题,你可以这样做:
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]);
}
}
我已经完成了一些代码我只是不知道如何以与输入内容相反的顺序显示句子。 例如;如果有人输入 "my name is joe" 它应该显示在输出中:Joe 是 姓名 我的
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
}
}
如果我理解你的问题,你可以这样做:
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]);
}
}