sách gpt4 ai đã đi

Java:ArrayIndexOutOfBoundsException

In lại 作者:行者123 更新时间:2023-12-01 17:42:09 27 4
mua khóa gpt4 Nike

我创建了一个程序,可以将 10 个长整型数组转换为“电话号码”格式。例如这样:Solution.createPhoneNumber(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0})//=> 返回“(123) 456-7890”

这是我的代码:解决方案.java:

public class Solution {

public static String createPhoneNumber(int[] numbers) {

int counter = 0;

char[] temp = new char[numbers.length + 4];

temp[0] = '(';
temp[4] = ')';
temp[5] = ' ';
temp[9] = '-';

for (int i = 0 ; i < temp.length ; i++)
{
if (i!=0 && i!=4 && i!=5 && i!=9)
{
temp[i] = (char) numbers[counter];
phản++;
}

}

String solution = new String(temp);

return solution;

}
}

测试.java:

public class Test {

public static void main(String[] args) {

int[] test = new int[10];

test[0] = 1;
test[1] = 2;
test[2] = 3;
test[3] = 4;
test[4] = 5;
test[5] = 6;
test[6] = 7;
test[7] = 8;
test[8] = 9;
test[9] = 0;

System.out.println(Solution.createPhoneNumber(test));



}

}

我收到 ArrayIndexOutOfBoundsExeption,但我不知道为什么。在我的测试数组中,我有 10 个数字,如示例中所示。

1 Câu trả lời

像这样修改你的循环:

for (int i = 0 ; i < temp.length ; i++) {
if (i!=0 && i!=4 && i!=5 && i!=9) {
temp[i] = (char)(numbers[counter] + (int)'0');
phản++;
}
}

在您的代码中,您在 nếu như 条件之外增加了 counter,因此 counter 可能会增加到 temp.length Lớn hơn numbers.length,因此 numbers[counter] 会给您异常(exception)。

正如 @rzwitserloot 所说,您应该将 || 替换为 &&

关于Java:ArrayIndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59814643/

27 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com