【问题标题】:java.lang.ArrayIndexOutOfBoundsException When I try to add a variable to an Array [duplicate]java.lang.ArrayIndexOutOfBoundsException 当我尝试将变量添加到数组时[重复]
【发布时间】:2023-04-09 05:02:01
【问题描述】:

我正在尝试通过扫描仪输入将数字保存到数组中,但是
“java.lang.ArrayIndexOutOfBoundsException”不断弹出。

这是我的代码:

for (int counter = 1;1==1;counter++) {
            int bucky[] = new int[counter];
            int scan = oof.nextInt();
            bucky[counter] = scan;
            if (counter == 5) {
                System.out.println(bucky);
            }

谁能解释我做错了什么或者我在思考过程中哪里出错了?

【问题讨论】:

标签: java arrays syntax


【解决方案1】:

试试

for (int counter = 1;1==1;counter++) {
            int bucky[] = new int[counter];
            int scan = oof.nextInt();
            bucky[counter-1] = scan;
            if (counter == 5) {
                System.out.println(bucky);
            }

一组 5 个位置 {0,1,2,3,4}

您的阵列有 1 个位置{0}

bucky[counter-1] = 扫描;

【讨论】:

  • 我得到了类似 [I@16d3586 的奇怪输出
  • 这是编译器的故障还是什么
  • @DudeManGuy 方便的经验法则:它从不编译器出现故障 (;->)
猜你喜欢
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 2021-10-05
  • 1970-01-01
  • 2022-06-14
  • 1970-01-01
  • 2015-05-06
相关资源
最近更新 更多