简体   繁体   中英

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

I just start a project and all i want to know is how to return a specific word while still having it be random. At the moment it just prints/returns the number of the position in the string. For example i want it to return "cat" and if it does the print " " for every letter in cat. I already have the code to print the " " for every letter i just need to get the word back instead of an int.

InstantiateRandom :

Random random = new Random();

Use it to get a random number*:

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

Print index of said random number:

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

* Note that normally you use something like random.nextInt(max - min + 1) + min but because your min is 0 and because of 0-based array indexes, you can just use words.length in this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM