易混淆点2:方法中类类型数组的初始化
以汽车租赁系统举例,目前车库中的数组虽然写进了方法体中,但是因为测试类中车库的方法没调用,只有调用了这个车库,数组中才会有真正的内容,所以在测试类中先调一下车库的方法。
GarageRoom garageRoom = new GarageRoom();
garageRoom.put();//这句等于将车库中的数组初始化了
1.车库类代码块:
package com.qf.test1;
public class GarageRoom {
Vehicle[] vehicles = new Vehicle[8];
public void put() {
vehicles[0] = new Car("宝马", "冀11111", 300, "x6");
vehicles[1] = new Car("宝马", "冀22222", 600, "x7");
vehicles[2] = new Car("别克", "冀33333", 300, "林荫小道");
vehicles[3] = new Car("别克", "冀44444", 600, "林荫大道");
vehicles[4] = new Bus("金杯", "浙55555", 800, 16);
vehicles[5] = new Bus("金杯", "浙66666", 1500, 34);
vehicles[6] = new Bus("金龙", "浙77777", 800, 16);
vehicles[7] = new Bus("金龙", "浙88888", 1500, 34);
}
public Vehicle foundVehicle(String type2,String type3,int seatNum) {
for (int i = 0; i < vehicles.length; i++) {
if (vehicles[i] instanceof Car) {
Car car = (Car) vehicles[i];
if (car.getBrand().equals(type2) && car.getType().equals(type3)) {
return car;
}
}else if (vehicles[i] instanceof Bus) {
Bus bus = (Bus) vehicles[i];
if (bus.getBrand().equals(type2) && bus.getSeatCount() == seatNum) {
return bus;
}
}
}
return null;
}
}
2.测试类代码块:
package com.qf.test1;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// GarageRoom garageRoom = new GarageRoom();
// garageRoom.put();
System.out.println("********欢迎来到风驰天下、大运摩托网上汽车租赁公司********");
Scanner input = new Scanner(System.in);
System.out.println("请输入您想要租赁的汽车类型:1.轿车 2.客车");
String type1 = input.nextInt() == 1 ? "轿车" : "客车" ;
String type2 = "";
String type3 = "";
int seatNum = 0;
if (type1.equals("轿车")) {
System.out.println("请输入您想要租赁的轿车品牌:1.宝马 2.别克");
type2 = input.nextInt() == 1 ? "宝马" : "别克";
if (type2.equals("宝马")) {
System.out.println("请输入您想要租赁的汽车种类:1.x6 2.x7");
type3 = input.nextInt() == 1 ? "x6" : "x7" ;
}else if (type2.equals("别克")) {
System.out.println("请输入您想要租赁的汽车种类:1.林荫小道 2.林荫大道");
type3 = input.nextInt() == 1 ? "林荫小道" : "林荫大道" ;
}
}else if (type1.equals("客车")) {
System.out.println("请输入您想要租赁的客车品牌:1.金杯 2.金龙");
type2 = input.nextInt() == 1 ? "金杯" : "金龙";
if (type2.equals("金杯")) {
System.out.println("请输入您想要租赁的客车座位数:1.16座 2.34座");
seatNum = input.nextInt() == 1 ? 16 : 34 ;
}else if (type2.equals("金龙")) {
System.out.println("请输入您想要租赁的客车座位数:1.16座 2.34座");
seatNum = input.nextInt() == 1 ? 16 : 34 ;
}
}
GarageRoom garageRoom = new GarageRoom();
garageRoom.put();
System.out.println("请输入您要租赁的天数:");
int days = input.nextInt();
garageRoom.foundVehicle(type2, type3, seatNum);
System.out.println("分配给您的车牌号是:"+ garageRoom.foundVehicle(type2, type3, seatNum).getId());
System.out.println("您需要支付的租赁费用是" + garageRoom.foundVehicle(type2, type3, seatNum).price(days));
}
}