Reputation: 15
I made 2 1-D arrays, and want to sort the values of a 2-D array so they can divide amongst the 1-D arrays.
For context, I'm making a program that utilizes user input to create a 2-D array organizing salaried and hourly employees.
The user inputs the number of employees they want to store in the employeeDatabase. Then they input the ID numbers (employeeList) and finally whether each employee is salaried or hourly (1 or 2) This data is then stored into a 2-D array.
As an example, here's a sample employeeDatabase.
EmployeeID | Salaried (1) or Hourly (2) |
---|---|
123456 | 1 |
654321 | 2 |
I want it to output: Employee 123456 is a salaried employee. Employee 654321 is an hourly employee.
I want to separate the values in the employeeDatabase into arrays salariedEmployees and hourlyEmployees but I keep getting "ArrayIndexOutOfBoundsException: 0" arrays. The snippet of code that causes problems is below. Thank you!
int salariedEmployeesSize = 0;
int hourlyEmployeesSize = 0;
int[] salariedEmployees = new int[salariedEmployeesSize];
int[] hourlyEmployees = new int[hourlyEmployeesSize];
for (int i = 0; i < employeeList.length - 1; i++) {
if (employeeDatabase[i][1] == 1) {
salariedEmployeesSize += 1;
salariedEmployees[i] = employeeDatabase[i][0];
} else if (employeeDatabase[i][1] == 2) {
hourlyEmployeesSize += 1;
hourlyEmployees[i] = employeeDatabase[i][0];
}
}
for (int i = 0; i < salariedEmployees.length - 1; i++) {
System.out.println("Employee " + salariedEmployees[i] + " is a salaried employee.");
}
for (int i = 0; i < hourlyEmployees.length - 1; i++) {
System.out.println("Employee " + hourlyEmployees[i] + " is an hourly employee.");
}
Upvotes: 0
Views: 128
Reputation: 541
You have to resize the array each time you add an element. in java, this is done by:
The old array will not be referenced anymore and will be destroyed by the jvm's garbage collector.
Note: Your Question will probably be marked as duplicate, I encourage you to search for the answers :).
References you can search on:
Upvotes: 1