任务是检查句子中每个单词中的数字,找到数字最大的单词,同时也是 3 的幂。我在这里做了所有事情,它工作正常,直到我在句子中的最后一个单词句子以数字结尾
例如:
输入:Iam8 you64 asjkj125 asdjkj333 heis216 : OutOfBounds
输入:Iam8 you64 asjkj125 asdjkj333 heis216s : heis216s 是目标词
然后它就会出界,我已经(至少我认为我是)发现了哪里,但我不知道如何在不改变这个计算思路的情况下避免这种情况。
这是发生这种情况的代码:
for (int i = 0; i < r.length(); i++) {
current+= r.charAt(i);
if (r.charAt(i) == ' ' || i = r.length()-1) {
for (int j = 0; j < current.length(); j++) {
while ((int) current.charAt(j) > 47 && (int) current.charAt(j) < 58) {
// If the last character of the last word is a digit, j increments and we end up out of bounds.
br = br + current.charAt(j);
j++;
}
<小时/>
最佳答案
current
即使在处理最后一个字符串后,仍在处理,因此 StringIndexOutOfBoundsException
发生异常。因为current
正在处理字符串,检查 j
应该有长度 current
。添加j < current.length()
的检查在while
像这样循环while ( j<current.length() && (int) current.charAt(j) > 47 && (int) current.charAt(j) < 58)
.
关于java - 越界异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47975401/