I';我想从字符串中随机抽取一个词。JAVA

I';我想从字符串中随机抽取一个词。JAVA,java,string,random,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 = n

我被指派从字符串中随机抽取一个单词。所有的单词都有相同的字母。到目前为止,我收集的工具有:灵长类数据类型及其方法。到目前为止,我已经:

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

    }

}

谢谢您的时间和考虑。

这是一种更干净的方法。你的方法也很好,但是这个方法很清楚,也很容易理解

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

        }    
    }

这是一种更干净的方法。你的方法也很好,但是这个方法很清楚,也很容易理解

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

        }    
    }

问题是什么?你是在和我们分享你的答案,还是有一个问题被巧妙地掩盖了?我走对了吗,或者我应该使用子字符串来代替?为什么不直接使用split,你会得到一个字符串数组,你可以随机索引这些字符串作为参考。问题是什么?你是在和我们分享你的答案,还是有一个巧妙地隐藏在其中的问题?我走的路对吗,或者我应该改用子字符串吗?为什么不直接使用split,您将得到一个字符串数组,您可以随机索引这些字符串以供参考。