我有一个作业来制作一个程序来读取用户输入并将其从数组中删除。在我的作业中,我需要使用一个新数组,该数组从第一个数组中获取元素而不读取元素。但是当我运行时我的程序以NullPointerException结尾。
我试图给我的新数组一个值,但是没有用。我也尝试使我的第二个数组的第一个数组的长度为-1,它的工作原理是将所有元素打印为空
private void removeEmployee() {
Scanner in = new Scanner(System.in);
String[] employees = {"John Smith", "Michael Hawkins", "Bruce Lee", "Johnny Depp", "Marshall Mathers"};
String[] newEmployees = null;
System.out.println("There are 5 employees:");
for (int i = 0; i < employees.length; i++) {
System.out.println(employees[i]);
}
System.out.println("Enter an employee name to remove");
String remove = in.nextLine();
for (int i = 0; i < employees.length; i++) {
if (remove == employees[i]) {
for (int j = 0; j < i; j++) {
newEmployees[j] = employees[j];
}
for (int index = i; index < employees.length - 1; index++) {
newEmployees[index] = employees[index + 1];
}
}
break;
}
for (int i = 0; i < employees.length - 1; i++) {
System.out.println(newEmployees[i]);
}
}
如上所述,我有2个结果: 1.如果String [] newEmployees = null;它给我NullPointerException错误 2.If String [] newEmployees = String [employees.length -1];它用4个元素打印出我的字符串(消除了一个)null