public static void selectEMployee() {
if (list1.isEmpty()) {
System.out.println("The list is empty");
}else {
System.out.println("The list of employees are");
for (Employee emp : list1) {
System.out.println("Name::" + emp.getName() + "t EmpId::"
+ emp.getEmpid() + "t Address::" + emp.getAddress()
+ "tphone::" + emp.getPhone());
}
}
}
当列表为空时,我想显示"列表为空",但它抛出异常?
空的 list
对象与尚未分配为list
引用的 list
类型变量之间存在差异。
即检查list1 == null
.如果空性null
,请不要测试空虚,因为你会得到NullPointerException
。
把它放在一起,写if (list1 == null || list1.isEmpty()){
代替。这是安全的,因为 Java 从左到右评估if
语句,并在获得明确答案后停止。
应用这个小修复程序,它将起作用:
if (list1 == null || list1.isEmpty()) {
System.out.println("The list is empty");
}
试一次
public static void selectEMployee() {
if (list1!=null && !list1.isEmpty()) {
System.out.println("The list of employees are");
for (Employee emp : list1) {
System.out.println("Name::" + emp.getName() + "t EmpId::"
+ emp.getEmpid() + "t Address::" + emp.getAddress()
+ "tphone::" + emp.getPhone());
}
} else {
System.out.println("The list is empty");
}
}
似乎您的 list1-var 没有初始化。您应该通过以下方式检查:
if(list1 == null || list1.isEmpty())
public static void selectEMployee() {
if (list1.isEmpty() || list1==null) //changes made here{
System.out.println("The list is empty");
}// this is not allowed here
} else {
System.out.println("The list of employees are");
for (Employee emp : list1) {
System.out.println("Name::" + emp.getName() + "t EmpId::"
+ emp.getEmpid() + "t Address::" + emp.getAddress()
+ "tphone::" + emp.getPhone());
}
}
你正在关闭 } for 方法之前,如果其他 for 循环关闭