2017-10-13 122 views
-1
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中

+0

是System.out.print'(MovieNames.get(r.nextInt(MovieNames.size)))'...這是已經非常接近你所需要的。問題是什麼? –

+0

放行:System.out.print(MovieNames.get(r.nextInt(MovieNames.size)));讀取循環之外(並將大括號()添加到size())。 –

回答

0

您應該實例化一個ArrayList,讀取所有電影標題並將它們添加到列表中,然後使用Random.nextInt()選擇並打印它。

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 
    } 
} 
+0

它的工作,但現在我不能打印出整個MovieList文件,它給了我「null」 –

+0

@Troy Nguyen看到我上面編輯的版本,打印MovieList。或者,如果您使用Java 8,則可以用MovieNames.forEach(System.out :: println)替換每個循環; – smitty1

+0

當我創建隨機r = new Random();它是一個字符串var?所以我想用replaceAll方法將隨機名替換成「__」「,但是我不能使用var r,java說它找不到符號。 –