-1

此代码有效,但它不断给我数组越界异常。即使我将数组大小更改为 6 并在最后留下 2 个空槽,它也会引发异常。有人可以找出问题吗?

  int [] arrayCMYK = new int [4];
  getCMYK(arrayCMYK);

static int getCMYK (int arrayCMYK[])
   {
   Scanner input = new Scanner(System.in);
   //C
   System.out.println("\n\nPlease Enter the 'C' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[0] = input.nextInt();

   while(arrayCMYK [0] > 100 || arrayCMYK [0] < 0 )
   {
   System.out.println("\n\nError\nPlease Enter the 'C' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[0] = input.nextInt();
   }
   //M
   System.out.println("\n\nPlease Enter the 'M' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[1] = input.nextInt();

   while(arrayCMYK [1] > 100 || arrayCMYK [1] < 0 )
   {
   System.out.println("\n\nError\nPlease Enter the 'M' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[1] = input.nextInt();
   }
   //Y
   System.out.println("\n\nPlease Enter the 'Y' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[2] = input.nextInt();

   while(arrayCMYK [2] > 100 || arrayCMYK [2] < 0 )
   {
   System.out.println("\n\nError\nPlease Enter the 'Y' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[2] = input.nextInt();
   }
   // K
   System.out.println("\n\nPlease Enter the 'K' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[3] = input.nextInt();

   while(arrayCMYK [3] > 100 || arrayCMYK [3] < 0 )
   {
   System.out.println("\n\nError\nPlease Enter the 'K' value of the CMYK number.");
   System.out.println("Press Enter after the number has been entered.");
   arrayCMYK[3] = input.nextInt();
   }
   return arrayCMYK[4];
4

4 回答 4

2

数组的索引从 0 到 n-1,因此在您定义大小为 4 的数组时,您将拥有索引 0、1、2 和 3。当您 时return arrayCMYK[4];,您超出了界限。

于 2013-01-15T19:24:47.347 回答
1

数组的索引是从零开始的,所以

int [] arrayCMYK = new int [4];

有索引 0 - 3

arrayCMYK[4]会给你 ArrayOutOfBoundsException

于 2013-01-15T19:25:46.937 回答
0

这个 4 的索引超出了范围:

return arrayCMYK[4];

您定义的 arrayCMYK 有一个由 4 个整数组成的数组。因此,有效索引为 0、1、2 和 3。您对位置 4 的访问导致数组超出范围异常。

于 2013-01-15T19:25:37.807 回答
0
return arrayCMYK[4];

您声明了一个包含 4 个元素的数组。Java 中的数组是零索引的。

因此,您只能参考 0-3

于 2013-01-15T19:27:21.777 回答