本文介绍了从数组列表随机字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在开始从阵列中随机字的问题。我不知道如何引用的话数组列表从中获取。有人可以把我在为我的getRandomWord类朝着正确的方向?谢谢!
一个方法getRandomWord这需要什么作为输入并返回从字一个随机字符串。
请记住,您可以使用Random类来做到这一点。
进口java.io. *;
进口的java.util。*;
进口了java.util.Random;公共类单词表{ 私人的ArrayList<串GT;话; //从文件构造字符串
公共静态无效构造函数(字符串文件名)抛出IOException异常{ ArrayList的字=新的ArrayList();
阅读的BufferedReader =新的BufferedReader(新的FileReader(文件名));
串行= read.readLine();
而(行!= NULL){
字词。(线);
//线= reader.readline();
}
} 公共静态无效getRandomWord(){
随机兰特=新的随机();
串randomWord = words.get(rand.nextInt(words.size));
}
}
解决方案
这将帮助你,我觉得这是能够从一个字符串数组
获得一个随机字 私有静态的String [] =名称{终结者,切片,忍者,牛,机器人,littlegirl};
NAME =名称[(INT)(的Math.random()* names.length)];
的System.out.println(名);
I'm having an issue initiating a random word from the array. I'm not sure how to refer to the words arraylist to fetch from it. Can someone put me in the right direction for my getRandomWord class? Thanks!
A method getRandomWord which takes nothing as input and returns a random String from words.Remember that you can use the Random class to do this.
import java.io.*;
import java.util.*;
import java.util.Random;
public class WordList{
private ArrayList<String> words;
//Construct String from file
public static void constructor(String filename) throws IOException{
ArrayList words = new ArrayList();
BufferedReader read = new BufferedReader(new FileReader("filename"));
String line = read.readLine();
while (line != null){
words.add(line);
//line = reader.readline();
}
}
public static void getRandomWord(){
Random rand = new Random();
String randomWord = words.get(rand.nextInt(words.size));
}
}
解决方案
This will help you I think It's able to get a random word from an array of strings
private static String[] names = { "Terminator", "Slicer","Ninja", "cow", "Robot", "littlegirl" };
name = names[(int) (Math.random() * names.length)];
System.out.println(name);
这篇关于从数组列表随机字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!