【问题标题】:ArrayIndexOutOfBoundsException - ArrayLengthArrayIndexOutOfBoundsException - ArrayLength
【发布时间】:2019-06-19 19:59:08
【问题描述】:

Please click here to see my task's screenshot

你好,能帮帮我吗?我的代码有什么问题?我知道我的 Array 的长度或 If 语句有问题,但我无法找到它。

非常感谢!

import java.util.Scanner;

 class TripleSwapping {

 public static void main(String[] args) {

     Scanner in = new Scanner(System.in);
     System.out.println("Please enter the count of your elements: ");
     int count = in.nextInt();

     System.out.println("Your array before sorting: ");
     int A[] = new int [count];
     for (int i = 0; i < 10; i++) {
         A[i]=in.nextInt();
    }
     boolean changed =false;
     do {
         for (int i = 0; i < A.length-1; i++) {
             if (!(A[i+1]>A[i]) && !(A[i+1] > A[i+2])) {
                 int temp;
                 temp = A[i];
                 A[i]= A[i+1];
                 A[i+1] =temp;
               }
         }
         for (int i = 0; i < A.length-1; i++) {
             if (A[i] >A[i+1]) {
                  int temp;
                 temp = A[i];
                 A[i]= A[i+1];
                 A[i+1] =temp;
               changed=true;  
             }

         }


     }while(changed);

     System.out.println("Your array after swapping");

     for (int i = 0; i < A.length; i++) {
         System.out.println(A[i]);
     }

}

}

【问题讨论】:

  • 请将您的代码复制并粘贴到您的问题中。请不要链接到您的教科书的图像。这没有帮助。
  • @markspace 是的,我忘记添加我的代码,现在我添加了,非常感谢你提醒我:)
  • 错误不是告诉你在哪一行你越界了吗?
  • 我能看到的最简单的罪魁祸首是在分配 count 变量时:int count = in.nextInt()。如果你读到一个小于 10 的 int,那么你接下来执行的 for 循环:for (int i =0; i&lt;10; i++) 将抛出异常。
  • 嗯,还需要异常跟踪——你得到的异常的全文。它应该有行号。另外请用注释指出哪一行是实际错误,因为我们无法从您的代码中看到行号。

标签: java arrays sorting indexoutofboundsexception swap


【解决方案1】:

你得到 ArrayIndexOutOfBoundsException 因为如果你输入小于 10 就会抛出异常。

for (int i = 0; i < 10; i++) {
    A[i]=in.nextInt();
}

改为使用

for (int i = 0; i < count; i++) {
    A[i]=in.nextInt();
}

【讨论】:

  • 最好使用i &lt; A.length。由于 count 被重新分配给其他值,因此出错的可能性较小。
  • 是的!您也可以检查0 值
  • 你有什么意见?
猜你喜欢
  • 2020-12-06
  • 1970-01-01
  • 1970-01-01
  • 2011-12-03
  • 2014-05-19
  • 2013-02-25
  • 2013-12-28
  • 2017-06-27
  • 1970-01-01
相关资源
最近更新 更多