java - 数组索引越界 - Java 递归方法
问题描述
我正在用 3 种不同的方法编写一个程序来练习递归。我已经成功实施了三个中的一个,但我现在有点卡在第二个上。此方法尝试计算字符数组中“微笑”(:)) 的数量。我以为我写得对,但是当我测试它时,我不断收到 ArrayIndexOutOfBoundsException,但我不知道为什么。我的方法如下:
public static int countSmiles(char[] letters, int index) {
int smileCounter = 0;
//If the array is less than 2 in length it cannot include ":)".
if(letters.length < 2) {
return 0;
}
//If there is a smile increment the counter.
else if(letters[index] == ':') {
if(letters[index+1] == ')') {
smileCounter++;
}
}
//Increment the index
index++;
//Recursive assignment
smileCounter = countSmiles(letters, index);
//Return number of smiles
return smileCounter;
}
我正在测试的方法如下:
public static void main(String[] args) {
char[] JavaCharArray = {'r', 's', 't', 'u', ':', ')', 'v'};
System.out.println(countSmiles(JavaCharArray, 0));
}
从我的代码来看,我尝试访问的索引 (0) 似乎不是负数,也不大于提供的数组。我真的只是不明白。
解决方案
在递归方法中,您需要一个停止条件。尝试:
...
if(letters.length < 2) {
return 0;
}
if (index + 2 > letters.length) {
return 0;
}
...
推荐阅读
- pine-script - 仅在特定日期编辑系列
- eloquent - Laravel 雄辩地更新 JSON 列一些字段而不覆盖其他所有内容
- javascript - Expo:“错误:无法在设备上获取 GCM 令牌”
- windbg - 将 Windbg 与 Qemu 一起使用时无法读取 PsLoadedModuleList
- tensorflow - Pure TensorFlow vs Keras // Tensorflow 解决了问题,但 Keras 没有 - 何时使用 Keras,何时使用 TensorFlow?
- r - 如何只选择包含 [YYYY-MM-DD] 的行?
- javascript - PHP 没有向 XHR 发送完整的响应?
- sql - SQL逗号分隔符列表用单个qoutes替换每个值
- java - 发送 ArrayList
作为使用 Retrofit Android 的一部分 - node.js - GraphQL 仅在查询中请求某个字段时才获取