gpt4 book ai didi

java - 我想从大的 arr 复制到两个小的 arr

转载 作者:行者123 更新时间:2023-12-02 06:13:09 27 4
gpt4 key购买 nike

我想将自己的值输入到 20 个大数组中,并将其复制到 2 个 10 个小数组中,然后必须打印第二个数组的值。我收到错误 ArrayIndexOutOfBoundsException 我的代码有什么问题。 =|

 Scanner in = new Scanner(System.in);
int[] test = new int[20];
int[] testA = new int[10];
int[] testB = new int[10];
for (int i = 0; i < test.length; i++){
test[i] = in.nextInt();
}
for(int i = 0; i < 10; i++){
testA[i]= test[i];
}
for (int i = 10; i < test.length; i++ ){
testB[i] = test[i];
System.out.println(testB[i]);

最佳答案

在第二个循环的第一步中,您将为 testB[10] 赋值,这会导致错误,因为 testB 的大小仅为 10 (即[0~9])。

你需要改变

testB[i] = test[i];
System.out.println(testB[i]);

testB[i-10] = test[i];
System.out.println(testB[i-10]);

或者您可以使用:

for (int i = 0; i < 10; i++ ){
testB[i] = test[i+10];
System.out.println(testB[i]);
}

关于java - 我想从大的 arr 复制到两个小的 arr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21708925/

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