[英]Convert a 2D array into a 1D array error
我已經編寫了一個程序,但是有一個問題,我不知道在哪里,但是它認為它是int轉換。 我想從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
所有這些都在方法內部,那么我該如何解決?
嘗試:
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.