gpt4 book ai didi

java - java方法中的字符串索引超出范围错误

转载 作者:行者123 更新时间:2023-11-30 09:40:01 27 4
gpt4 key购买 nike

我正在用 java 创建一个棋盘游戏引擎,我想创建一个方法来计算每个玩家剩下的项目数量,这是我的代码:

public class ChessBoard
{
private boolean belongsToPlayer(char piece, int player)
{
if (player == 0 && Character.isUpperCase(piece))
return true;
if (player == 1 && Character.isLowerCase(piece))
return true;
return false;
}

final public int getCount(final String[] board, final int player) {
int count = 0;
int size = board.length;
for (int i = 1; i < size; i++) {
for (int j = 1; j < size; j++) {
if (belongsToPlayer(board[i].charAt(j), player)) {
count++;
}
}
}
return count;
}
}

但问题是我得到的字符串索引超出范围@ if (belongsToPlayer(board[i].charAt(j), player))任何人都知道如何解决这个问题?

最佳答案

board[i] 的长度显然比size 短。如果您的意图是遍历字符串的每个字符,请将循环更改为:

        for (int j = 0; j < board[i].length(); j++) {
if (belongsToPlayer(board[i].charAt(j), player)) {
count++;
}
}

关于java - java方法中的字符串索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9639300/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com