public class Program3 {
public static void main(String[] args)
{
}
public static int getCoins(int[][] map, int row, int col)
{
int cointotal = map[row][col];
int[] numbers = new int[4];
int big = 0;
int a = map[row-1][col];
int b = map[row-1][col-1];
int c = map[row][col-1];
int d = map[row+1][col];
while(a > cointotal || b > cointotal || c > cointotal || d > cointotal)
{
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
numbers[3] = d;
big = findLargest(numbers);
cointotal = cointotal + big;
a = map[row-1][col];
b = map[row-1][col-1];
c = map[row][col-1];
d = map[row+1][col];
if(numbers[0] == big)
{
row = row -1;
col = col;
}
if(numbers[1] == big)
{
row = row - 1;
col = col - 1;
}
if(numbers[2] == big)
{
row = row;
col = col - 1;
}
if(numbers[3] == big)
{
row = row + 1;
col = col;
}
}
return cointotal;
}
public static int findLargest(int[] numbers){
int largest = numbers[0];
for(int i = 1; i < numbers.length; i++){
if(numbers[i] > largest){
largest = numbers[i];
}
}
return largest;
}
}
答案 0 :(得分:1)
您的数字数组的大小为3,因此从0到2。
int[] numbers = new int[3];
但是你正在访问第4个元素
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
numbers[3] = d; //OutOfBound
尝试
int[] numbers = new int[4];
修改强>
我建议,在访问数组之前验证索引。
int rowLength = map.length;
int columnLength = (rowLength==0)0:map[0].length;
//other code
boolean verify(int x, int y){
return x < rowLength && y < columnLength;
}
//then you can do something like this
int a = verify(row-1,col)? map[row-1][col]: a; //don't change if the index is outOfBounds