java - 我不断收到错误“索引 5 超出长度 5 的范围”但不知道要更改什么
问题描述
我对编码很陌生,所以请多多包涵,我只是在尝试洗牌数组的方法,以便最终在我用 Java 创建的纸牌游戏中洗牌。我知道索引 5 超出了长度 5 的范围,但令我困惑的是错误不会总是弹出。有时我尝试运行我的代码并且它工作得很好,有时我得到错误,即使我在运行它的时间之间没有更改任何内容。
public class Card{
public static void shuffle(Object[] array) {
int noOfCards = array.length;
for (int i = 0; i < noOfCards; i++) {
int s = i + (int)(Math.random() * (noOfCards - 1));
Object temp = array[s]; //this is the first line it says has a problem
array[s] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
String[] strOfCards = {"A","B","C","D","E"};
Card.shuffle(strOfCards); //this is the second line that has a problem
for(int i = 0; i < strOfCards.length; i++) {
System.out.println(strOfCards[i] + " ");
}
}
}
我不知道如何更改有缺陷的线条,欢迎提出任何建议!*** 我尝试更改字符串中的字母数,但随后错误随之更改,即“索引 6 超出长度 6 的范围”
解决方案
考虑以下几行:
for (int i = 0; i < noOfCards; i++) {
int s = i + (int)(Math.random() * (noOfCards - 1));
Object temp = array[s]; //this is the first line it says has a problem
i 从 0 变化到 noOfCards - 1 你的随机数表达式从 0 变化到 noOfCards - 2 所以 s 从 0 变化到 (2 * noOfCards) - 3
然后array[s]
将在 s >= noOfCards 时抛出异常
每次运行它都不会发生,因为有时随机数都恰好在 noOfCards 之下
如果您想与随机的其他卡交换,那么您可以尝试:
Random random = new Random();
int s = (i + random.nextInt(noOfCards - 1)) % noOfCards;
我知道您将此作为学习机会,但如果您不知道,有一种Collections.shuffle
方法可用于ArrayList
在一个命令中对集合进行混洗。
推荐阅读
- apache - 如何在 Apache 中添加检查,以便删除查询参数超过 800 个字符的任何请求
- vb.net - 如何在 Microsoft Visual Studio Express 2012 for Web 的工具箱中添加功能?
- apple-sign-in - 苹果登录授权返回错误:操作无法完成。(com.apple.AuthenticationServices.AuthorizationError 错误 1000。)
- powershell - 来自远程系统的 Powershell 中的本地管理员组
- javascript - 如何自动将数据从 json 文件传递到组件中?
- php - 通过 JSON 列的键加入在 MySQL 5.6 中给出错误但在 MySQL 8.0.19 中工作
- python - 如何在聚合字段中创建字典/对象/映射
- nlp - 如何通过无监督方法学习数据到文本 NLG 中的语义对齐?
- sqlite - SQLite - load_extension 切换问题
- reactjs - 在 React 中使用 useState 和 useEffect 的无限循环