242 - 租车服务
Time Limit: 1000 Memory Limit: 65535
Submit: 181 Solved: 146
Description
某租车公司提供租车服务,针对不同的车辆类型,日租金的计算方式不同,具体地,对于货车而言,根据载重量load(单位是吨)计算,公式为load*1000;对于大型客车而言,根据车内座位数seats计算,公式为seats*50;对于小型汽车而言,根据车辆等级和折旧年数计算,公式为200*level/sqrt(year),其中sqrt表示平方根。设计合适的类继承结构实现上述功能,构造租车公司类CarRentCompany,提供静态函数rentVehicles,能够给定一组待租车辆,计算日租金总额。 在main函数中,读入多个车辆数据,并计算总的日租金。
Input
汽车数量 汽车种类 该类汽车相关属性 其中1表示货车,2表示大型客车,3表示小型汽车
Output
总的日租金,保留两位小数
Sample Input
3 1 3 2 50 3 5 5
Sample Output
5947.21
HINT
Pre Append Code
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int c = sc.nextInt();
Vehicle[] vs = new Vehicle[c];
for (int i=0;i<c;i++) {
int type = sc.nextInt();
Vehicle v = null;
if (type == 1) {//货车
vs[i] = new Truck (sc.nextDouble());
} else if (type == 2) {
vs[i] = new Keche(sc.nextInt());
} else if (type == 3) {
vs[i] = new Car(sc.nextInt(), sc.nextInt());
}
}
System.out.printf("%.2f",CarRentCompany.rentVehicles(vs));
}
}
Post Append Code
针对不同的车辆类型,日租金的计算方式不同
即要写抽象类实现多态
答案:
abstract class Vehicle {
public abstract double countmoney();
}
class Truck extends Vehicle {
double load;
public Truck(double load) {
super();
this.load = load;
}
@Override
public double countmoney() {
// TODO Auto-generated method stub
return load*1000;
}
}
class Keche extends Vehicle {
int seats;
public Keche(int seats) {
super();
this.seats = seats;
}
@Override
public double countmoney() {
// TODO Auto-generated method stub
return seats*50;
}
}
class Car extends Vehicle {
int level,year;
public Car(int level, int year) {
super();
this.level = level;
this.year = year;
}
@Override
public double countmoney() {
// TODO Auto-generated method stub
return 200*level/Math.sqrt(year);
}
}
class CarRentCompany {
public static double rentVehicles(Vehicle []h)
{
double rent = 0;
for(Vehicle i : h)
rent += i.countmoney();
return rent;
}
}