简体   繁体   中英

How can I print out a shuffled ArrayList?

How can I print out a shuffled ArrayList? This is what I have so far:

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();
        }

    }

In order to remove the single null-value, you should only read (and add to the collection) as long as there are lines.

In your code, you set the string to null , your reader can't read anything else, and adds the String (which is still null ) to the List. After that, you check, if the String is null and leave your loop!

Change your loop to this:

// 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();
}

Try this.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM