Click here to Skip to main content
15,900,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can resolve this error?
error occurred when I used "
Integer.parseInt(values[2])
"


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at Test.main(Test.java:20)

What I have tried:

Java
String path1 = "C:\\Users\\savac\\OneDrive\\Desktop\\Proiect\\RStudenti.csv";
		String line1 = "";
		Student[] studenti=new Student[2];
		try {int i=0;
			BufferedReader br = new BufferedReader(new FileReader(path1));

			while((line1 = br.readLine())!=null) {
				String[] values = line1.split(",");
				studenti[i]=new Student(values[0],values[1],Integer.parseInt(values[2]));
				i++;
			}
		}catch(FileNotFoundException e){
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
Posted
Updated 3-Aug-22 0:23am

Error:index 2 out of bounds for length 2 at test.main

Pretty clear from error that there seems to be only 2 values in an array object (corresponding to index 0 & 1), thus while accessing index 2, it throws an error.


studenti[i]=new Student(values[0],values[1],Integer.parseInt(values[2]));

Suspecting, mostly this line. You must have passed only 2 values comman separated as input leading to an error when you tried to access values[2]


Couple of suggestions:
1. Make sure to check for length before accessing the index
2. Use IDE Debugger and it would be easy to figure whats wrong. You will learn more when you do.
 
Share this answer
 
Quote:
ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

Very simple !
You try to use the third value of an array which contain only 2 values.
You need to check the size of the array.
Do something like:
Java
while((line1 = br.readLine())!=null) {
	String[] values = line1.split(",");
	if (size of values >= 3) {
		studenti[i]=new Student(values[0],values[1],Integer.parseInt(values[2]));
	} else {
		// report wrong contain of 'values'
		// print 'line1' and 'i'
	}
	i++;
}

I let you search for exact syntax.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900