由于程序基本没有什么方法,故没有使用接口。直接用父类Car代表皮卡车,子类SeatCar和LoadCar分别代表客车和货车。
- 首先是一个父类Car,表示能载货又能载客的车
public class Car {
public int id;//序号
public String name;//车名
public int seat;//座位数
public double load;//载重量
public double price;//租金
public Car(int id, String name, int seat, double load, double price) {
this.id = id;
this.name = name;
this.seat = seat;
this.load = load;
this.price = price;
}
public String toString() {//重写toString方法以便返回信息
return id + ".\t" + name + "\t" + seat + "\t" + load + "\t" + price;
}
}
- 货车类LoadCar
public class LoadCar extends Car {
public LoadCar(int id, String name, double load, double price) {
super(id, name, 0, load, price);//货车直接将载人数设为0
}
public String toString() {
return id + ".\t" + name + "\t" + seat + "\t" + load + "\t" + price;
}
}
- 客车类SeatCar
public class SeatCar extends Car {
public SeatCar(int id, String name, int seat, double price) {
super(id, name, seat, 0, price);//客车直接将载货量设为0
}
public String toString() {
return id + ".\t" + name + "\t" + seat + "\t" + load + "\t" + price;
}
}
- 测试程序
import java.util.Scanner;
public class Initial {
public static void main(String[] args) {
int totalSeat = 0;
double totalLoad = 0;
double totalPrice = 0;
String loadCarList = "";// 利用字符串存储可载货车辆的列表
String seatCarList = "";// 利用字符串存储可载人车辆的列表
Car[] cars = new Car[5];
// 此处运用多态原理,用父类的引用指向子类对象,可以放在同一个数组中方便遍历
cars[0] = new SeatCar(1, "奥迪A4", 4, 500);
cars[1] = new SeatCar(2, "马自达6", 4, 400);
cars[2] = new Car(3, "皮卡雪6", 4, 2, 450);
cars[3] = new LoadCar(4, "松花江", 4, 400);
cars[4] = new LoadCar(5, "依维柯", 200, 1000);
System.out.println("欢迎使用达达租车系统");
System.out.println("您是否要租车:1是 0否");
Scanner in = new Scanner(System.in);
if (in.nextInt() == 1) {
System.out.println("***************目前可租车型***************");
System.out.println("序号\t汽车名称\t载人(人)\t载货(吨)\t租金(元/天)");
for (Car c : cars) {// foreach遍历并输出可租车辆
System.out.println(c);// 由于重写了toString()方法,此处直接输出toString()的返回值
}
System.out.println("请输入您要租车的数量:");
int number = in.nextInt();
for (int i = 0; i < number; i++) {
System.out.println("请输入第" + (i + 1) + "辆车的序号:");
int id = in.nextInt();
totalSeat += cars[id - 1].seat;
totalLoad += cars[id - 1].load;
totalPrice += cars[id - 1].price;
if (cars[id - 1].seat != 0) {
seatCarList = seatCarList + cars[id - 1].name + " ";
}
if (cars[id - 1].load != 0) {
loadCarList = loadCarList + cars[id - 1].name + " ";
}
}
System.out.println("请输入租车天数:");
int day = in.nextInt();
System.out.println("\n*****您的账单*****");
if (loadCarList == "") {// 防止输出空字符串的情况发生
System.out.println("无可载货的车辆");
} else {
System.out.println("可载货的车辆有:" + loadCarList);
System.out.println("总载货量:" + totalLoad);
}
if (seatCarList == "") {
System.out.println("无可载人的车辆");
} else {
System.out.println("可载人的车辆有:" + seatCarList);
System.out.println("总载人数:" + totalSeat);
}
System.out.println("总价格:" + day * totalPrice + '元');
} else {
System.out.println("感谢您的使用!");
}
in.close();
}
}
- 运行结果预览
点击查看更多内容
27人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦