I am getting an exception and i don´t understand why
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;
for (int i = 1; i <= 3; i++) {
System.out.println("Please type the number " + i + ":");
numbers[i] = input.nextInt();
total = total + numbers[i];
}
System.out.println("The average of the 3 number is: " + total / n);
}
Console:
Please type the number 1:
3
Please type the number 2:
4
Please type the number 3:
5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Ejercicio12.main(Ejercicio12.java:17)
asked Feb 9, 2019 at 20:11
5
because array index start at 0
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;
for (int i = 0; i <= 2; i++) {
int row=i+1;
System.out.println("Please type the number " + row + ":");
numbers[i] = input.nextInt();
total = total + numbers[i];
}
System.out.println("The average of the 3 number is: " + total / n);
}
answered Feb 9, 2019 at 20:17
4
Indexes starts from 0. Your length is 3 and your counter variable (i
) starts from 1.
You can use
for (int i = 0; i < 3; i++)
answered Feb 9, 2019 at 21:16
Try this, insert this inside your main method
Scanner input = new Scanner(System.in);
int n = 3;
int[] numbers = new int[n];
float total = 0;
for (int i = 0; i < 3; i++) {
System.out.println("Please type the number " + (i + 1) + ":");
numbers[i] = input.nextInt();
total = total + numbers[i];
}
System.out.println("The average of the 3 number is: " + total / n);
answered Feb 21, 2020 at 11:11
1
If you’re facing error listed below
Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
var arr = arrayOf("One","Two","Three")
println(arr[3])
In this Array we just defined three values and index start from 0, So Index 3 doesn’t exist in array that’s why it’s giving this Exception
Try to print index value which includes in Array Such As
println(arr[1])
answered Feb 19, 2022 at 5:29
Rehan KhanRehan Khan
96911 silver badges9 bronze badges
Появляется ошибка Exception in thread «main» java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at practice/practice.Practic2.main(Practic2.java:65). Если убрать for(подписан), ошибка пропадает. При его появлении, даже пустом, появляется.
Основной код.
public static void main(String[] args) {
// TODO Auto-generated method stub
int i, j = 0;
int indexI = 0, indexJ = 0;
double temp;
boolean isPresent = false, isPresentMin = false;
double Array[] [] = new double[3] [3];
Array[0][0] = 0;
Array[0][1] = 3;
Array[0][2] = 1;
Array[1][0] = 2;
Array[1][1] = 8;
Array[1][2] = 2;
Array[2][0] = 4;
Array[2][1] = -1;
Array[2][2] = 7;
Matrix.showArray(Array);
if (Array[0][0] != 1) {
for (i = 0; i < Array.length;i++) {
for (j = 0; j < Array.length; j++) {
if (1 == Array[i][j]) {
indexI = i;
indexJ = j;
isPresent = true;
break;
}}
if (isPresent == false) {
for (j = 0; j < Array.length; j++) {
if (-1 == Array[i][j]) {
indexI = i;
indexJ = j;
isPresent = true;
break;
}}
} else break;
}
System.out.println(indexI + " " + indexJ );
System.out.println("-----------");
i = 0; j = 0;
if (isPresent == true) {
for(j =0; i < Array.length; i++) {
if (Array[i][j] == 1 | Array[i][j] == -1) {
break;
}
if (i == Array.length -1) {
Matrix.transferCol(Array, indexI, indexJ);
break;
}
}
Matrix.showArray(Array);
if (Array[0][0] == 1 | Array[0][0] == -1) {
} else Matrix.transferRow(Array, indexI, indexJ);
indexI = 0; indexJ = 0; j = 0; i=2;
System.out.println("indexI = "+indexI+"indexJ = "+indexJ+"i = "+ i +"j = "+j);
for (i=1;i<=Array.length;i++) { //данный for вызывает ошибку
temp = Array[i][j]/Array[indexI][indexJ]; //65 строка
for(j = 0;j < Array.length;j++) {
Array[i][j] = Array[i][j] - temp * Array[indexI][j];
}}}
}Matrix.showArray(Array);
}
}
Класс Matrix
public class Matrix {
public static void transponArray(double Array[][]) { //Метод транспонирования матрицы
int i,j;
for (i =0; i < 3; i++) {
for (j =i+1; j< 3; j++) {
double temp = Array[i][j];
Array[i][j] = Array[j][i];
Array[j][i] = temp;
}
}
for (i = 0; i<3; i++) {
for (j = 0; j<3; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
}
public static void showArray(double Array[][]) { //метод показа матрицы
for (int i = 0; i < Array.length; i++) {
for (int j = 0; j < Array.length; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
System.out.println("-----------");
}
public static void transferCol(double Array[][], int indexI, int indexJ) { //метод переставления столбцов
int i = 0, j = 0;
double temp;
for (j = indexJ;i<Array.length;i++) {
temp = Array[i][0];
Array[i][0] = Array[i][j];
Array[i][j] = temp;
}
for (i=0;i<Array.length;i++) {
for(j=0;j<Array.length;j++) {
Array[i][j] = Array[i][j] * -1;
}
}}
public static void transferRow(double Array[][], int indexI, int indexJ) { //метод переставления строк
int i =0, j = 0;
double temp;
for (i = indexI;j<Array.length;j++) {
temp = Array[0][j];
Array[0][j] = Array[i][j];
Array[i][j] = temp;
}
for (i=0;i<Array.length;i++) {
for(j=0;j<Array.length;j++) {
Array[i][j] = Array[i][j] * -1;
}
}
}
}
Posted by Marta on March 4, 2022
Viewed 7817 times
In this article, you will learn the main reason why you will face the java.lang.ArrayIndexOutOfBoundsException Exception in Java along with a few different examples and how to fix it.
I think it is essential to understand why this error occurs, since the better you understand the error, the better your ability to avoid it.
This tutorial contains some code examples and possible ways to fix the error.
Watch the tutorial on Youtube:
What causes a java.lang.ArrayIndexOutOfBoundsException?
The java.lang.ArrayIndexOutOfBoundsException error occurs when you are attempting to access by index an item in indexed collection, like a List or an Array. You will this error, when the index you are using to access doesn’t exist, hence the “Out of Bounds” message.
To put it in simple words, if you have a collection with four elements, for example, and you try to access element number 7, you will get java.lang.ArrayIndexOutOfBoundsException error.
To help you visualise this problem, you can think of arrays and index as a set of boxes with label, where every label is a number. Note that you will start counting from 0.
For instance, we have a collection with three elements, the valid indexes are 0,1 and 2. This means three boxes, one label with 0, another one with 1, and the last box has the label 2. So if you try to access box number 3, you can’t, because it doesn’t exist. That’s when you get the java.lang.ArrayIndexOutOfBoundsException error.

The Simplest Case
Let’s see the simplest code snippet which will through this error:
public class IndexError { public static void main(String[] args){ String[] fruits = {"Orange", "Pear", "Watermelon"}; System.out.println(fruits[4]); } }
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
Although the error refer to arrays, you could also encounter the error when working with a List, which is also an indexed collection, meaning a collection where item can be accessed by their index.
import java.util.Arrays; import java.util.List; public class IndexError { public static void main(String[] args){ List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon"); System.out.println(fruits.get(4)); } }
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
Example #1: Using invalid indexes in a loop
An instance where you might encounter the ArrayIndexOutOfBoundsException exception is when working with loops. You should make sure the index limits of your loop are valid in all the iterations. The loop shouldn’t try to access an item that doesn’t exist in the collection. Let’s see an example.
import java.util.Arrays; import java.util.List; public class IndexError { public static void main(String[] args){ List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon"); for(int index=0;index<=fruits.size();index++){ System.out.println(fruits.get(index)); } } }
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 Orange Pear Watermelon at java.base/java.util.Arrays$ArrayList.get(Arrays.java:4351) at com.hellocodeclub.IndexError.main(IndexError.java:11)
The code above will loop through every item in the list and print its value, however there is an exception at the end. The problem in this case is the stopping condition in the loop: index<=fruits.size()
. This means that it will while index is less or equal to 3, therefore the index will start in 0, then 1, then 2 and finally 3, but unfortunately 3 is invalid index.
How to fix it – Approach #1
You can fix this error by changing the stopping condition. Instead of looping while the index is less or equal than 3, you can replace by “while index is less than 3”. Doing so the index will go through 0, 1, and 2, which are all valid indexes. Therefore the for loop should look as below:
for(int index=0;index<fruits.size();index++){
That’s all, really straightforward change once you understand the root cause of the problem. Here is how the code looks after the fix:
import java.util.Arrays; import java.util.List; public class IndexError { public static void main(String[] args){ List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon"); for(int index=0;index<fruits.size();index++){ System.out.println(fruits.get(index)); } } }
Output:
How to fix it – Approach #2
Another way to avoid this issue is using the for each syntax. Using this approach, you don’t have to manage the index, since Java will do it for you. Here is how the code will look:
import java.util.Arrays; import java.util.List; public class IndexError { public static void main(String[] args){ List<String> fruits = Arrays.asList("Orange", "Pear", "Watermelon"); for(String fruit: fruits){ System.out.println(fruit); } } }
Example #2: Loop through a string
Another example. Imagine that you want to count the appearances of character ‘a’ in a given sentence. You will write a piece of code similar to the one below:
public class CountingA { public static void main(String[] args){ String sentence = "Live as if you were to die tomorrow. Learn as if you were to live forever"; char [] characters = sentence.toCharArray(); int countA = 0; for(int index=0;index<=characters.length;index++){ if(characters[index]=='a'){ countA++; } } System.out.println(countA); } }
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 73 out of bounds for length 73 at com.hellocodeclub.dev.CountingA.main(CountingA.java:8)
The issue in this case is similar to the one from the previous example. The stopping condition is the loop is right. You should make sure the index is within the boundaries.
How to fix it
As in the previous example, you can fix it by removing the equal from the stopping condition, or by using a foreach and therefore avoid managing the index. See below both fixes:
public class CountingA { public static void main(String[] args){ String sentence = "Live as if you were to die tomorrow. Learn as if you were to live forever"; int countA = 0; for(Character charater: sentence.toCharArray()){ // FOR EACH if(charater=='a'){ countA++; } } System.out.println(countA); } }
Output:
Conclusion
In summary, we have seen what the “java.lang.ArrayIndexOutOfBoundsException” error means . Additionally we covered how you can fix this error by making sure the index is within the collection boundaries, or using foreach syntax so you don’t need to manage the index.
I hope you enjoy this article, and understand this issue better to avoid it when you are programming.
Thank you so much for reading and supporting this blog!
Happy Coding!



У вас в коде это далеко не единственная ошибка. Читайте мой ответ по этому вопросу (все замечания касаются и вашего кода). Нужна помощь: java.lang.ArrayIndexOutOfBoundsException
Результаты таковы:
import java.util.Scanner;
public class Pr5 {
public static void main(String[] args) {
double[][] sourceArray = inputArray();
//вывод матрицы в виде таблицы
for (int i = 0; i < sourceArray.length; i++) {
for (int j = 0; j < sourceArray[i].length; j++)
System.out.printf("%6.2f", sourceArray[i][j]);
System.out.println();
}
double [] resultArray = calculate(sourceArray);
//выводим новый массив
for (int i = 0; i < resultArray.length; i++) {
System.out.printf("Массив: x(%d) = %1.2fn", i, resultArray[i]);
}
}
private static double[][] inputArray() {
double[][] sourceArray;
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Rows = ");
int rows = scanner.nextInt();
System.out.print("Columns = ");
int column = scanner.nextInt();
sourceArray = new double[rows][column];
for (int i = 0; i < sourceArray.length; i++) {
for (int j = 0; j < sourceArray[i].length; j++) {
System.out.print("x(" + i + "," + j + ")=");
sourceArray[i][j] = scanner.nextDouble();
}
}
}
return sourceArray;
}
//произведения четных строк матрицы
public static double[] calculate(double[][] array) {
double [] result = new double [array.length/2+1];
for (int i = 0; i < array.length; i = i + 2) { //четные строки
double increase = 1;
for (int j = 0; j < array[i].length; j++) {
if ((array[i][j] % 1 == 0)) increase *= array[i][j];
}
result[i/2] = increase;
}
return result;
}
}
А раз у нас отдельный метод отвечает за расчеты и создание результирующего массива, мы можем написать юнит тест для отладки
import org.junit.Test;
import static org.junit.Assert.*;
public class Pr5Test {
@Test
public void testCalculate() {
System.out.println("calculate");
double[][] x = {{2,3.5,5},{1,3,8},{4,7,9}};
double[] expResult = {10D, 252D};
double[] result = Pr5.calculate(x);
assertArrayEquals(expResult, result, 0.0001);
}
}
Я оставил ваши методы статическими, но это не отменяет того, о чем я говорил в указанном ответе.
The ArrayIndexOutOfBoundsException
is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
Since the ArrayIndexOutOfBoundsException
is an unchecked exception, it does not need to be declared in the throws
clause of a method or constructor.
What Causes ArrayIndexOutOfBoundsException
The ArrayIndexOutOfBoundsException
is one of the most common errors in Java. It occurs when a program attempts to access an invalid index in an array i.e. an index that is less than 0, or equal to or greater than the length of the array.
Since a Java array has a range of [0, array length — 1], when an attempt is made to access an index outside this range, an ArrayIndexOutOfBoundsException
is thrown.
ArrayIndexOutOfBoundsException Example
Here is an example of a ArrayIndexOutOfBoundsException
thrown when an attempt is made to retrieve an element at an index that falls outside the range of the array:
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
String[] arr = new String[10];
System.out.println(arr[10]);
}
}
In this example, a String
array of length 10 is created. An attempt is then made to access an element at index 10, which falls outside the range of the array, throwing an ArrayIndexOutOfBoundsException
:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at ArrayIndexOutOfBoundsExceptionExample.main(ArrayIndexOutOfBoundsExceptionExample.java:4)
How to Fix ArrayIndexOutOfBoundsException
To avoid the ArrayIndexOutOfBoundsException
, the following should be kept in mind:
- The bounds of an array should be checked before accessing its elements.
- An array in Java starts at index
0
and ends at indexlength - 1
, so accessing elements that fall outside this range will throw anArrayIndexOutOfBoundsException
. - An empty array has no elements, so attempting to access an element will throw the exception.
- When using loops to iterate over the elements of an array, attention should be paid to the start and end conditions of the loop to make sure they fall within the bounds of an array. An enhanced for loop can also be used to ensure this.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!