2013-08-18 28 views
1

我對java很陌生,一直試圖讓我的軸承。我一直在試圖寫一個概念員工數據庫的證明。這一切都正常工作,直到我輸入最後一個僱員條件,然後我得到一個ArrayIndexOutOfBoundsException。這是我的兩個文件的代碼。任何幫助,將不勝感激。ArrayIndexOutOfBounds員工數據庫程序異常

import java.util.Scanner; 
public class EmployeeInterface 
{ 
    public static void main(String[] args) 
    { 
     Scanner Input = new Scanner(System.in); 

     System.out.println("Please enter the number of employees to register."); 
     int employeeCount = Input.nextInt(); 
     Employee.setEmployeeNumber(employeeCount); 
     String employeeFullName; 
     String employeeAddress; 
     String employeeDateOfHire; 

     for(int x = 0; x <= employeeCount; x++) 
     { 
      System.out.println("Please enter the full name of employee number " + (x + 1)); 
      Input.nextLine(); 
      employeeFullName = Input.nextLine(); 
      System.out.println("Please enter the address of employee number " + (x + 1)); 
      employeeAddress = Input.nextLine(); 
      System.out.println("Please enter the date of hire for employee " + (x + 1)); 
      employeeDateOfHire = Input.nextLine(); 

      Employee.employeeRegister(x, employeeFullName, employeeAddress, employeeDateOfHire); 
     } 
    } 
} 

這裏是第二個文件:

public class Employee 
{ 
    private static int employeeCount; 
    private static String employees[][] = new String[employeeCount][4]; 

    public static void setEmployeeNumber(int x) 
    { 
     employeeCount = x; 
    } 

    public static void employeeRegister(int employeeNumber, String employeeFullName, String address, String employeeHireDate) 
    { 
     employees[employeeNumber][0] = employeeFullName; 
     employees[employeeNumber][1] = employeeFullName; 
     employees[employeeNumber][2] = employeeFullName; 
     employees[employeeNumber][3] = employeeFullName; 
    } 
} 
+0

概念驗證?如何編寫GUI? –

回答

7

這就是問題所在:

for(int x = 0; x <= employeeCount; x++) 

您使用<=而非<。所以,如果employeeCount是3,你實際上問的員工的詳細信息,並使用索引0,1,2和3 - 但3對3的大小的數組

setEmployeeCount無效指數方法是中斷 - 它更改值employeeCount,但不重新初始化數組,因此您將始終以大小爲0的數組結束。鑑於您說代碼一直工作到最終條目,我懷疑這不是你的真實代碼中的問題,否則你會在第一個條目中得到一個例外。

這就是說,我會強烈建議您創建一個較爲有用Employee類型與號碼,姓名等私人例如場......然後創建一個List<Employee>。 (有可能是在它沒有通過點靜態字段存儲在Employee或者 - ?如果你想要兩個員工名單)

此外,一個employeeHireDate應該在一些適當的時間類型 - 不是一個字符串。 (我從Joda Time作爲建議使用LocalDate內置的Java類型日期/時間類型是可怕的。)

2

除了其他答案:

private static String employees[][] = new String[employeeCount][4]; 

EMPLOYEECOUNT立即intialized爲0等之後是數組。

您需要在設置employeeCount後重新設置陣列。

0

你的循環迭代了1個額外的時間。如果employeeCount是5,則循環重複6次。 試試這個

for(int x = 0; x < employeeCount; x++) 
0
ArrayIndexOutOfBounds Exception 

因爲你試圖通過使用for(int x = 0; x < employeeCount; x++)

,而不是

<=,而不是隻 <

使用更不存在訪問1個指數

for(int x = 0; x <= employeeCount; x++)` 
0

除了其他答案:

在方法setEmployeeNumber(int x)中,您只更改變量employeeCount。這裏缺少的是調整存儲員工的陣列大小:

employees[][] = new String[employeeCount][4];