![](/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.