cars =new ArrayList<Car>();
cars.add(new Car(2016,"honda","civic"));
cars.add(new Car(2017,"Lamborghini","aventador"));
cars.add(new Car(2000,null,"caravan"));
cars.add(new Car(2010,"dodge",null));
我该如何打印和跳过空值:
hondacivicLamborghiniaventadorcaravandodge
答案 0 :(得分:0)
请勿添加 null
,只需将其替换为 ""
:
示例:
cars.add(new Car(2000,"","caravan"));
cars.add(new Car(2010,"dodge",""));
代码:
List<Car> cars = new ArrayList<Car>();
cars.add(new Car(2016,"honda","civic"));
cars.add(new Car(2017,"Lamborghini","aventador"));
cars.add(new Car(2000,"","caravan"));
cars.add(new Car(2010,"dodge",""));
for(Car c : cars) {
System.out.print(c.getCompanyName() + "" + c.getCarName());
}
或者将代码更新为此,以跳过null
值:
for(Car c : cars) {
String data = ((c.getCompanyName() != null) ? c.getCompanyName(): "") + ((c.getCarName() != null) ? c.getCarName() : "");
System.out.print(data);
}