我已经制作了一个节目,但是我有一个问题而且我不知道在哪里,但它认为它在转换中。我想从2d转换为1d。 所以我有这个代码:
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为0 所以首先我扫描一下这个数字。 但是,当我想将所有这些数字收集到另一个数组1d时,它不会工作,我得到错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at project1.Project1.addRecord(Project1.java:90)
at project1.Project1.main(Project1.java:48)
Java结果:1
这一切都在一个方法中 那我怎么能解决这个问题?
答案 0 :(得分:2)
尝试:
net_salary[employee_counter]= salary_detail[0][employee_counter]+salary_detail[1][employee_counter]+salary_detail[2][employee_counter];
数组的第一个索引是0,所以最后一个将是2而不是3.因为你的数组只有3的长度,你试图访问索引3处的项目(这实际上是第四项)你得到的是java.lang.ArrayIndexOutOfBoundsException
。