【问题标题】:Return a specific word in a string of multiple words in java在java中返回多个单词的字符串中的特定单词
【发布时间】:2019-03-30 07:29:42
【问题描述】:
public class test{

     //my words
        private static String[] words = {"apple", "banana", "cat", "dog", "elf", "frog" };

    public static void main(String[] args) {
       int randomWord = (int) (Random() * words.length);

        System.out.println(randomWord);

    }//end string   
}//end class

我刚开始一个项目,我只想知道如何返回一个特定的单词,同时让它仍然是随机的。目前它只是打印/返回字符串中的位置数。例如,我希望它返回“cat”,如果它为 cat 中的每个字母打印“”。我已经有了为每个字母打印“”的代码,我只需要取回单词而不是 int。

【问题讨论】:

  • 你知道如何访问数组中的元素吗?
  • System.out.println(words[randomWord]);

标签: java string random int return


【解决方案1】:

实例化Random:

Random random = new Random();

用它来获取随机数*:

int randomNumber = random.nextInt(words.length);

所述随机数的打印索引:

System.out.println(words[randomNumber]);

*请注意,通常您使用 random.nextInt(max - min + 1) + min 之类的东西,但因为您的 min0 并且由于基于 0 的数组索引,您可以在此示例中只使用 words.length

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2018-09-15
    • 2015-05-14
    • 1970-01-01
    • 2018-05-14
    • 2021-06-22
    • 2019-01-11
    相关资源
    最近更新 更多