繁体   English   中英

Java越界异常

[英]Out of bounds exception Java

这段代码可以正常工作,但它始终为我提供数组超出范围的异常,即使我将数组大小更改为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];

数组的索引从0到n-1,因此,在您定义大小为4的数组的情况下,索引将为0、1、2和3。 return arrayCMYK[4];时,索引为0 return arrayCMYK[4]; ,您超出范围。

数组的索引从零开始,因此

int [] arrayCMYK = new int [4];

索引为0-3

arrayCMYK[4]将为您提供ArrayOutOfBoundsException

该索引4超出范围:

return arrayCMYK[4];

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

return arrayCMYK[4];

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

因此您只能参考0-3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM