【问题标题】:Display array of words in reverse order以相反的顺序显示单词数组
【发布时间】:2016-04-21 22:36:29
【问题描述】:

我已经完成了一些代码,只是不知道如何以与输入内容相反的顺序显示句子。 例如;如果有人输入“我的名字是乔” 它应该显示在输出中: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
     }
 }

【问题讨论】:

  • 你知道如何使用System.out.print(),你知道如何访问数组中的元素吗?如果是,那么您有什么问题?那我猜你不是写这段代码的人。
  • 谢谢,只是如何显示它而不是输入的内容。
  • 在对其他 Stack Overflow 帖子中的用例进行详尽调查后,您发现了什么?
  • 我只在 C++ 中找到了与此相关的问题,而不是 Java。

标签: java string token tokenize sentence


【解决方案1】:

如果我了解您的问题,您可以这样做:

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

【讨论】:

  • 谢谢你,我明白你在那里做了什么。
猜你喜欢
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
  • 1970-01-01
相关资源
最近更新 更多