简体   繁体   中英

I'm trying to pull a random word from a string. Java

I was given the assignment to pull a random word from a string. All the words have the same letters. The tools that I have gathered so far are: primative data types, and their methods. So far I have:

import java.util.Random;

public class HolyCow {

    public static void main(String[] args) {

        String threeLetterWords = "cat nat bat sat fat ";
        String newString = new String(threeLetterWords);
        int newStringLength = newString.length();
        int firstWord = newString.indexOf("cat ");
        int secondWord = newString.indexOf("nat ");
        int thirdWord = newString.indexOf("bat ");
        int fourthWord = newString.indexOf("sat ");
        int fifthWord = newString.indexOf("fat ");
        Random randomWord = new Random();
        System.out.print("Printing a random substring: " 
                + randomWord.nextInt(0 (newStringLength / 4)));

    }

}

Thank you for your time and consideration.

This is much cleaner way of doing it. Your method is also good but this one is clear and easy to understand

public class HolyCow {

        public static void main(String[] args) {

            String threeLetterWords = "cat nat bat sat fat ";
            String [] arr = threeLetterWords.split(" ");
            Random randomWord = new Random();
            System.out.print("Printing a random substring: " + arr[randomWord.nextInt(arr.length)]);

        }    
    }

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