我试图从字符串中拉出一个随机字。 Java的

时间:2013-09-26 23:19:41

标签: java string random

我被赋予从字符串中拉出一个随机单词的赋值。所有的单词都有相同的字母。到目前为止,我收集的工具包括:主要数据类型及其方法。到目前为止,我有:

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)));

    }

}

感谢您的时间和考虑。

1 个答案:

答案 0 :(得分:2)

这是更清洁的方式。你的方法也很好,但这个方法清晰易懂

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)]);

        }    
    }