2016-09-22 4 views
0

シャッフルされたArrayListをプリントアウトするにはどうすればよいですか?これはこれまで私が持っているものです:シャッフルされたArrayListを印刷するにはどうしたらいいですか?

public class RandomListSelection { 

    public static void main(String[] args) { 

     String currentDir = System.getProperty("user.dir"); 
     String fileName = currentDir + "\\src\\list.txt"; 

     // Create a BufferedReader from a FileReader. 
     BufferedReader reader = null; 
     try { 
      reader = new BufferedReader(new FileReader(
        fileName)); 
     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // Create ArrayList to hold line values 
     ArrayList<String> elements = new ArrayList<String>(); 

     // Loop over lines in the file and add them to an ArrayList 
     while (true) { 
      String line = null; 
      try { 
       line = reader.readLine(); 

       // Add each line to the ArrayList 
       elements.add(line); 

      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      if (line == null) { 
       break; 
      } 
     } 

     // Randomize ArrayList 
     Collections.shuffle(elements); 

     // Print out shuffled ArrayList 
     for (String shuffedList : elements) { 
      System.out.println(shuffedList); 
     } 


     // Close the BufferedReader. 
     try { 
      reader.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } 
+0

私はループの中でそれを初期化してきたように、ArrayListに私のファイルからの行を追加できるようにしたいです。それは悪いですか?コードを少し修正しました。 – santafebound

+0

これで、シャッフルされたArrayListが印刷されます。再び何が問題なのですか? –

+0

これでわかりました。見てみましょう。 – santafebound

答えて

2

1つのヌル値を削除するには、行がある限り、読み込み(コレクションに追加)する必要があります。

コードでは、文字列をnullに設定します。リーダーは他のものを読み取ることができず、文字列(まだnull)をリストに追加します。その後、文字列がヌルでループを離れるかどうかをチェックします。

これにあなたのループを変更

// Loop over lines in the file and add them to an ArrayList 
String line=""; 
try{ 
    while ((line=reader.readLine())!=null) { 
     elements.add(line); 
    } 
}catch (IOException ioe){ 
    ioe.printStackTrace(); 
} 
1

これを試してください。

public static void main(String[] args) throws IOException { 
    String currentDir = System.getProperty("user.dir"); 
    Path path = Paths.get(currentDir, "\\src\\list.txt"); 
    List<String> list = Files.readAllLines(path); 
    Collections.shuffle(list); 
    System.out.println(list); 
} 
関連する問題