You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio中用Java实现无重复随机单词展示(shuffle)

解决单词随机展示不重复的实现方案

你当前的代码每次点击都从完整单词数组里随机选,自然会出现重复。用Collections.shuffle()打乱列表后按顺序遍历,就能实现一轮内无重复、轮完再重新打乱的效果,具体实现如下:

步骤1:声明类成员变量

把单词列表和当前遍历索引提到类级别,避免每次点击重复读文件:

private List<String> wordList;
private int currentWordIndex = 0;

步骤2:初始化单词列表(建议在onCreate中执行)

只在页面初始化时读取一次文件,同时完成第一次打乱:

try {
    InputStream is = getAssets().open("challenges.txt");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();
    String text = new String(buffer);
    // 把数组转成ArrayList方便打乱操作
    wordList = new ArrayList<>(Arrays.asList(text.split("\n")));
    // 第一次打乱列表
    Collections.shuffle(wordList);
} catch (IOException ex) {
    ex.printStackTrace();
}

步骤3:修改随机单词方法

按打乱后的顺序取单词,遍历完一轮后重新打乱:

public void Random_Word(){
    if (wordList == null || wordList.isEmpty()) {
        return; // 空列表直接返回,避免崩溃
    }
    
    // 取当前索引对应的单词
    String targetWord = wordList.get(currentWordIndex);
    word.setText(targetWord);
    
    currentWordIndex++;
    // 遍历到列表末尾时,重新打乱并重置索引
    if (currentWordIndex >= wordList.size()) {
        Collections.shuffle(wordList);
        currentWordIndex = 0;
    }
}

额外说明

  • 原代码里的(int) (Math.random() * size - 1)存在数组越界风险:当Math.random()返回0时,计算结果为-1,会抛出数组索引异常,正确写法应该是(int)(Math.random() * size),不过用shuffle方案后就不需要这个逻辑了。
  • 把文件读取放在初始化阶段,能大幅提升点击按钮时的响应速度,避免重复IO操作。

内容的提问来源于stack exchange,提问作者user17765346

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 07:24:23