通过制作答答租车系统,复习了许多之前没有熟练掌握的知识。例如构造方法、私有变量的获取、继承后子类属性的初始化。之前想加入接口以应用所学到的相关知识。然后在代码实现过程中发现没有接口对于整个答答租车系统更简洁一些,也可能是我能力不足还不能实现的很好吧。以下是代码
/*父类Car*/
package com.imooc;
public abstract class Car{
public String CarName ;
public float Price ;
protected int Person ;
protected float Cargo ;
public void send(){} ;
}
/*轿车类*/
package com.imooc;
public class Auto extends Car{
public Auto(String newCarName , float newPrice , int newPerson){
CarName = newCarName ;
Price = newPrice ;
this.Person = newPerson ;
}
public void send(){
System.out.print(CarName + "\t" + Price +" 元/天\t" + "载人:" + Person +" 人\t");
}
public int getPeson(){
return Person ;
}
}
其他的货车,皮卡类大致相同。最后是主类
package com.imooc;
import java.util.Scanner ;
public class Initial {
public static void main(String args[]){
float money =0 , people = 0 , goods = 0;
Car CarRental[] = {new Auto("奥迪A4",500,4) , new Auto("马自达6",400,4),
new Auto("金龙",800,20) , new Truck("松花江",400,4),
new Truck("依维柯",1000,20) , new Pickup("皮卡雪6",450,4,2)} ;
System.out.println("欢迎使用答答租车系统:") ;
System.out.println("请问您是否使用租车系统:1是 2否") ;
Scanner scan = new Scanner(System.in) ;
String input = scan.nextLine() ;
if(input.equals("1")){
System.out.println("您可租车的类型及价目表:") ;
System.out.println("序号\t汽车名称\t租金\t 容量") ;
for(int i=0 ; i<CarRental.length ; i++){
System.out.print((i+1) + ".\t") ;
CarRental[i].send() ;
System.out.println();
}
System.out.println("请输入您需要租车的数目:") ;
int RentNum = scan.nextInt() ;
if(RentNum <= 0){
System.out.println("您的输入有误,请重新输入:") ;
System.out.println("请输入您需要租车的数目:") ;
RentNum = scan.nextInt() ;
}else{
int nums[] = new int[RentNum] ;
System.out.println("请输入您需要租车的天数:") ;
int RentDay = scan.nextInt() ;
if(RentDay <= 0){
System.out.println("您的输入有误,请重新输入:") ;
System.out.println("请输入您需要租车的天数:") ;
RentDay = scan.nextInt() ;
}else{
for(int i = 0 ;i < RentNum ; i++){
System.out.println("请输入您租用的第" + (i+1) + "辆车的序号: ") ;
int SerialNum = scan.nextInt() ;
if(SerialNum <= 0 || SerialNum > 6){
System.out.println("您的输入有误,请重新输入:") ;
System.out.println("请输入您租用的第" + (i+1) + "辆车的序号: ") ;
SerialNum = scan.nextInt() ;
}else{
nums[i] = SerialNum-1 ;
money += CarRental[nums[i]].Price ;
}
}
for(int i = 0 ; i < RentNum ; i++){
System.out.println("您选择的可载人类型的车辆为:") ;
if(CarRental[nums[i]] instanceof Auto || CarRental[nums[i]] instanceof Pickup){
people += CarRental[nums[i]].Person ;
System.out.print(CarRental[nums[i]].CarName + " ") ;
}
System.out.println("总载人数:" + people + "人") ;
}
for(int i = 0 ; i < RentNum ; i++){
System.out.println("您选择的可载货类型的车辆为:") ;
if(CarRental[nums[i]] instanceof Truck || CarRental[nums[i]] instanceof Pickup){
goods += CarRental[nums[i]].Cargo ;
System.out.print(CarRental[nums[i]].CarName + " ") ;
}
System.out.println("总载重:" + goods + "吨") ;
}
}
System.out.println("需付款:" + money*RentDay + "元");
}
}else{
System.exit(0) ;
}
}
}