我已经制作了一个程序,但我有一个问题,我不知道在哪里,但它认为这是转换。我想从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
所有这些都在一个方法中那么我该怎么解决呢?
try:
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
。