package com.imooc;
public class Car {
public int rent;
public String name;
public void dis()
{
System.out.print("\t\t"+name+"\t\t"+rent+"元/天");
}
}
子类载客的汽车
package com.imooc;
public class Lperson extends Car {
public int person;
public Lperson(String n,int p,int b){
super.name=n;
super.rent=p;
person=b;
}
public void dis()
{
super.dis();
System.out.print(" "+"载人:"+person+"人\n");
}
}
子类载货的汽车
package com.imooc;
public class Lbags extends Car {
public int bag;
public Lbags(String n,int p,int b){
super.name=n;
super.rent=p;
bag=b;
}
public void dis()
{
super.dis();
System.out.print(" "+"载货:"+bag+"吨\n");
}
}
子类即可载货又可载人的汽车
package com.imooc;
public class Lpb extends Car {
public int bag;
public int person;
public Lpb(String n,int p,int pe,int b){
super.name=n;
super.rent=p;
person=pe;
bag=b;
}
public void dis()
{
super.dis();
System.out.print("\t载人:"+person+"人 载货:"+bag+"吨\n");
}
}
程序运行主界面
package com.imooc;
import java.util.*;
public class UI {
public static void main(String[] args) {
// TODO Auto-generated method stub
Car c[]={new Lperson("奥迪A4",500,4),new Lperson("马自达6",400,4),
new Lpb("皮卡雪6 " ,450,4,2),new Lperson("金 龙",800,20),
new Lbags("松花江",400,4),new Lbags("依维柯",1000,20)};
System.out.println("欢迎使用答答租车系统:");
System.out.println("您是否要租车:1.是 2.否");
Scanner input=new Scanner(System.in);
int Choice=input.nextInt();
if(Choice==1){
System.out.println("您可租车类型及其价目表:");
System.out.println("序号\t\t汽车名称\t\t租金\t\t\t容量");
for(int i=1;i<=6;i++)
{
System.out.print(i);
c[i-1].dis();
}
System.out.println("请输入您要租车的数量:");
int Number=input.nextInt();
int a[]=new int[Number];
int j;
for(int i=0;i<Number;i++)
{
j=i+1;
System.out.println("请输入第"+j+"辆车的序号:");
a[i]=input.nextInt();
}
System.out.println("请输入租车天数:");
int Day=input.nextInt();
int sum=0;
int person=0;
int bag=0;
System.out.println("您的账单:");
System.out.println("***可载人的车有:");
for(int n=0;n<Number;n++)
{
if(a[n]==1a[n]==2a[n]==3a[n]==4)
{
System.out.print(c[a[n]-1].name+"\t\t");
if(c[a[n]-1] instanceof Lperson)
person+=((Lperson)c[a[n]-1]).person;
else if(c[a[n]-1] instanceof Lpb)
person+=((Lpb)c[a[n]-1]).person;
sum+= Day*c[a[n]-1].rent;
}
}
System.out.print("\n共载人:"+person+"人");
System.out.println("\n***可载货的车有:");
for(int n=0;n<Number;n++)
{
if(a[n]==3a[n]==5a[n]==6)
{
System.out.print(c[a[n]-1].name+"\t");
if(c[a[n]-1] instanceof Lbags)
{
bag+=((Lbags)c[a[n]-1]).bag;
sum+= Day*c[a[n]-1].rent;
//作为既能载客又能载货的,上面载客已经算过价格了
}
else if(c[a[n]-1] instanceof Lpb)
bag+=((Lpb)c[a[n]-1]).bag;
}
}
System.out.print("\n共载货:"+bag+"吨");
System.out.println("\n***租车总价格:"+sum+"元");
}
else
System.out.println("系统已结束!");
}
}
总结和反思:
1.用了if来作为操作的选择,只能操作一次,用while可以实现循环操作;
2.出现了父类到子类的强制类型转换,要注意溢出问题;
3.两次统计载客的车,载货的车都用了for循环遍历了所有的,增加了程序的时间复杂度,不是很好;
运行效果
热门评论
后面1a,2a,3a,4a,5a都表示的什么,没看懂,哥们