📜  随机播放或随机化Java的列表(1)

📅  最后修改于: 2023-12-03 15:28:51.459000             🧑  作者: Mango

随机播放或随机化Java的列表

在Java中,使用Collections类提供的shuffle()方法可以很方便地对列表进行随机化。shuffle()方法会随机地重新排列列表中的元素。

使用shuffle()方法随机化列表

下面是一个使用shuffle()方法随机化Java列表的例子:

import java.util.ArrayList;
import java.util.Collections;

public class ShuffleExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        list.add("apple");
        list.add("banana");
        list.add("orange");
        list.add("pear");
        System.out.println("Original List: " + list);
        Collections.shuffle(list);
        System.out.println("Shuffled List: " + list);
    }
}

输出结果如下:

Original List: [apple, banana, orange, pear]
Shuffled List: [banana, orange, pear, apple]
网上随机播放音乐列表的例子

下面是一个使用shuffle()方法随机播放Java音乐列表的例子:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class MusicPlayer {
    public static void main(String[] args) {
        ArrayList<String> playlist = new ArrayList<String>();
        playlist.add("Song 1");
        playlist.add("Song 2");
        playlist.add("Song 3");
        playlist.add("Song 4");
        playlist.add("Song 5");
        playlist.add("Song 6");
        playlist.add("Song 7");
        playlist.add("Song 8");

        Scanner scanner = new Scanner(System.in);

        while (true) {
            // 随机化列表
            Collections.shuffle(playlist);
            System.out.println("\nPlaying all songs in random order:\n");
            for (String song : playlist) {
                System.out.println("Playing " + song + "...");
            }
            
            // 询问是否再次随机播放
            System.out.println("\nDo you want to shuffle and play again? (y/n)");
            String input = scanner.nextLine();
            if (input.equalsIgnoreCase("n")) {
                break;
            }
        }
        scanner.close();
    }
}

输出结果如下:

Playing all songs in random order:

Playing Song 1...
Playing Song 7...
Playing Song 4...
Playing Song 2...
Playing Song 8...
Playing Song 6...
Playing Song 5...
Playing Song 3...

Do you want to shuffle and play again? (y/n)
y

Playing all songs in random order:

Playing Song 3...
Playing Song 8...
Playing Song 4...
Playing Song 7...
Playing Song 1...
Playing Song 2...
Playing Song 6...
Playing Song 5...

Do you want to shuffle and play again? (y/n)
n

以上就是使用Java随机播放或随机化列表的例子。