简体   繁体   中英

Convert a 2D array into a 1D array error

I have made a program, but I have a problem and I don't know where but it think its int the convertion. I want to convert from 2d to 1d. So I have this code:

            System.out.print("\nEnter the employee's (1) Basic Pay (2) Housing Allowance (3) Travel Allowance (example: 4000 500 300): ");
        salary_detail[0][employee_counter] = sc.nextDouble();
        salary_detail[1][employee_counter] = sc.nextDouble();
        salary_detail[2][employee_counter] = sc.nextDouble();
        net_salary[employee_counter]= salary_detail[1][employee_counter]+salary_detail[2][employee_counter]+salary_detail[3][employee_counter];

employee_counter is 0 So first of all I scan the number. But when I want to collect all of this numbers to another array 1d it won't work and I get the error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at project1.Project1.addRecord(Project1.java:90)
at project1.Project1.main(Project1.java:48)

Java Result: 1

all this is inside a method so how can i fix that ?

try:

net_salary[employee_counter]= salary_detail[0][employee_counter]+salary_detail[1][employee_counter]+salary_detail[2][employee_counter];

The first index of an array is 0, so the last will be 2 instead of 3. Since your array has only a length of 3 and you are trying to access the item at index 3 (this is actually the fourth item) you are getting an java.lang.ArrayIndexOutOfBoundsException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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