[英]How to only choose elements in an array with a specific length
public String[] words={"cat", "dog", "rodeo", "bird", "lookers", "skid");
。
// Picks a random word from the dictionary, given the length of the word
public String pickWord(int size)
{
}
因此,如果用户输入4,它将在单词数组中随机选择4个字母的单词,并随机选择。 我为此从Random类中创建了一个rand变量。 因此,如何在数组中选择与用户输入的字母数相同的元素。
这是一个应该可以解决您的问题的示例方法。
String[] words;
public String pickWord(int size){
List ls = new ArrayList<String>();
for(int i=0; i>words.length;i++){
if(words[i].length() == size){
ls.add(words[i]);
}
}
Collections.shuffle(ls);
if(ls.isEmpty()){
return null;
}
return (String) ls.get(0);
}
您可以非常简单地去做类似...的事情。
public String pickWord(int size) {
List<String> results = Arrays.stream(words).
filter((String t) -> t.length() == size).
collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(results);
return results.isEmpty() ? null : results.get(0);
}
像...
System.out.println(pickWord(3));
System.out.println(pickWord(4));
System.out.println(pickWord(5));
System.out.println(pickWord(6));
可以打印类似...
cat
skid
rodeo
null
从数组中提取长度等于输入的字符串,并将其放入列表中。 生成符合列表大小的随机整数,然后从列表中获取随机单词。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int maxLen;
ArrayList<String> list = new ArrayList();
String[] words = {"cat", "dog", "rodeo", "bird", "lookers", "skid"};
// Picks a random word from the dictionary, given the length of the word
System.out.println("Please input the max length of the word.");
maxLen = sc.nextInt();
for (String s : words) {
if (s.length() == maxLen) {
list.add(s);
}
}
System.out.println(pickWord(list));
}
static String pickWord(ArrayList<String> list) {
Random rd = new Random();
int randInt = rd.nextInt(list.size());
String picked = list.get(randInt);
return picked;
}
计算具有该长度的单词数。 如果为0,则返回null。 如果为1,则返回单词。 否则,使用Random.nextInt(count)
获取介于0
和count-1
之间的数字,然后找到该单词并将其返回。
您可以根据用户输入使用n个长度的单词生成一个新数组,并从新数组中提取随机索引,因为所有元素都适合指定的长度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.