我是java的新手,并且一直试图让我对它有所了解。我一直在努力写一个概念验证员工数据库。一切正常,直到我输入最后一个员工条件,然后我得到一个ArrayIndexOutOfBoundsException。这是我的两个文件的代码。任何帮助将不胜感激。
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 :(得分:7)
这是问题所在:
for(int x = 0; x <= employeeCount; x++)
您使用的是<=
而不是<
。因此,如果employeeCount
为3,您实际上会询问 4 员工的详细信息,并使用索引0,1,2和3 - 但3是数组的无效索引3号。
您的setEmployeeCount
方法也已损坏 - 它会更改employeeCount
的值,但不会重新初始化数组,因此您最终会得到一个数组大小为0.鉴于您已经说过代码在最终输入之前有效,我怀疑这不是您的真正的代码中的问题,否则您将在第一次获得异常条目。
那就是说,我强烈建议您创建一个更有用的Employee
类型,其中包含数字,名称等的私有实例字段...然后创建一个List<Employee>
。 (通过Employee
中的静态字段存储它可能没有意义 - 如果你想要两个员工列表怎么办?)
此外,employeeHireDate
应该是一些适当的时间顺序类型 - 而不是字符串。 (我建议使用Joda Time中的LocalDate
,因为日期/时间类型的内置Java类型很糟糕。)
答案 1 :(得分:2)
除了其他答案:
private static String employees[][] = new String[employeeCount][4];
employeeCount立即初始化为0,之后是数组。
您需要在设置employeeCount后重新设置数组。
答案 2 :(得分:0)
你的循环正在迭代1次额外的时间。如果employeeCount为5,则循环迭代6次。 试试这个
for(int x = 0; x < employeeCount; x++)
答案 3 :(得分:0)
ArrayIndexOutOfBounds Exception
因为您尝试使用<=
而不是<
来访问不存在的1索引
使用for(int x = 0; x < employeeCount; x++)
而不是
for(int x = 0; x <= employeeCount; x++)`
答案 4 :(得分:0)
除了其他答案:
在方法setEmployeeNumber(int x)
中,您只需更改变量employeeCount
。这里缺少的是调整存储员工的阵列的大小:
employees[][] = new String[employeeCount][4];