シャッフルされた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();
}
}
私はループの中でそれを初期化してきたように、ArrayListに私のファイルからの行を追加できるようにしたいです。それは悪いですか?コードを少し修正しました。 – santafebound
これで、シャッフルされたArrayListが印刷されます。再び何が問題なのですか? –
これでわかりました。見てみましょう。 – santafebound