![](/img/trans.png)
[英]Java Regex : How to return the whole word if the words ends with a specific string
[英]Return a specific word in a string of multiple words in java
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。
实例化Random
:
Random random = new Random();
用它来获得一个随机数*:
int randomNumber = random.nextInt(words.length);
打印所述随机数的索引:
System.out.println(words[randomNumber]);
*请注意,通常您使用random.nextInt(max - min + 1) + min
但因为您的min
为0
并且由于基于 0 的数组索引,您可以在此示例中仅使用words.length
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.