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文件中选择随机电影标题,我可以打印出整个列表,但我不确定如何随机选择其中一个。
答案 0 :(得分:0)
您应该实例化一个ArrayList,读取所有电影标题并将它们添加到列表中,然后使用Random.nextInt()选择一个并打印它。
答案 1 :(得分:0)
尝试这样的事情:
public class guessMovies {
public static void main(String[] args) throws IOException {
String MovieList;
ArrayList<String> MovieNames = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("Movielist.txt"))) {
while ((MovieList = br.readLine()) != null) {
MovieNames.add(MovieList);
}
for(String movieName: MovieNames){
System.out.println(movieName);
}
Random r = new Random();
System.out.println(MovieNames.get(r.nextInt(MovieNames.size())));
}
catch(FileNotFoundException exception) {
System.out.println("I cannot find your file");
}
//pick random movie
}
}