java中接收用户输入的一句英文,将其中的单词以反序输出。"hello c sharp"→"sharp c hello"
时间: 2023-12-31 11:03:24 浏览: 22
```
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a sentence: ");
String sentence = scanner.nextLine();
String[] words = sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
System.out.print(words[i] + " ");
}
}
}
```
相关问题
java接收用户输入的一句英文,将其中的单词以反序输出。"hello c sharp"→"sharp c hello"
```java
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一句英文: ");
String input = scanner.nextLine();
String[] words = input.split(" "); // 使用空格分割单词
for (int i = words.length - 1; i >= 0; i--) { // 从最后一个单词开始输出
System.out.print(words[i] + " ");
}
}
}
```
用户输入一句英文,将其中的单词以反序输出,例如:hello c sharp
好的,您的问题是如何将用户输入的英文句子中的单词以反序输出?
可以使用以下步骤:
1. 将用户输入的英文句子按照空格划分为单词列表。
2. 对单词列表进行反转操作。
3. 将反转后的单词列表拼接成字符串输出。
下面是一个示例代码实现:
```python
s = input("请输入英文句子:")
words = s.split()
words.reverse()
res = " ".join(words)
print(res)
```
输入示例:
```
请输入英文句子:hello c sharp
```
输出示例:
```
sharp c hello
```