我的任务是从字符串中随机抽取一个单词。所有单词都有相同的字母。到目前为止我收集的工具是:原始数据类型及其方法。到目前为止我已经:
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)]);
}
}
关于java - 我正在尝试从字符串中随机抽取一个单词。 java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19040269/