public class guessMovies {
private Random randomGenerator;
public static void main(String[] args) throws IOException {
String MovieList = null;
try (BufferedReader br = new BufferedReader(new FileReader("Movielist.txt"))) {
while ((MovieList = br.readLine()) != null) {
ArrayList<String> MovieNames = new ArrayList<String>();
MovieNames.addAll(Arrays.asList(MovieList));
//System.out.println(MovieList);
System.out.println(MovieNames);
Random r = new Random();
System.out.print(MovieNames.get(r.nextInt(MovieNames.size)));
}
}
catch(FileNotFoundException exception) {
System.out.println("I cannot find your file");
}
//pick random movie
}
有人可以指導我如何選擇在Movielist文件隨機電影標題,我可以打印出整個列表,但我不知道如何選擇其中一個隨機。檢索隨機元素的ArrayList中
是System.out.print'(MovieNames.get(r.nextInt(MovieNames.size)))'...這是已經非常接近你所需要的。問題是什麼? –
放行:System.out.print(MovieNames.get(r.nextInt(MovieNames.size)));讀取循環之外(並將大括號()添加到size())。 –