[英]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.