打完代码后看了不少同学的例子,有人载人载货都设了子类,有的在Main中用switch,有的用挺多的变量,我个人喜欢简单点,在这没细分class,用了一些for来循环那堆数组,发过来给大家看看,可以聊聊~
类 Ademocar (最初想搞抽象类玩玩,结果好像用处不大。。。)
public class Ademocar {
public String carname;
public int carno;
public int price;
public int people;
public int load;
public Ademocar(int carno, String carname, int price, int people, int load){//建构方法
this.carno = carno;
this.carname = carname;
this.price = price;
this.people = people;
this.load = load;
}
public String toString() {
return carno+". "+ carname +"\t" + price + " 元/天\t" + people + "人\t" + load + "吨";
}
public String check(String type){ //返回车名
if(type=="h" && this.people>0){
return this.carname + " ";
}
else if(type=="c" && this.load>0){
return this.carname + " ";
}
return "";
}
}
在这我没在数据保护上多整,有空的话可以设置set和get方法,更安全。
Main 方法
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("你是否要租车?");
int get = scan.nextInt();
if (get==1){
Ademocar car1 = new Ademocar(1,"奥迪A4",500,4,0);
Ademocar car2 = new Ademocar(2,"马自达6",400,4,0);
Ademocar car3 = new Ademocar(3,"皮卡雪6",450,4,2);
Ademocar car4 = new Ademocar(4,"金龙 ",800,20,0);
Ademocar car5 = new Ademocar(5,"松花江",400,0,4);
Ademocar car6 = new Ademocar(6,"依维柯",1000,0,20);
Ademocar[] car = {car1,car2,car3,car4,car5,car6}; //装对象
System.out.println("以下是所有车:");
System.out.println("序号 汽车名称\t租金\t\t容量");//第一行
for(int t=0;t<6;t++)
System.out.println(car[t]);//显示所有车
System.out.println("请选择租车数量:");
get = scan.nextInt();
int[] cars = new int[get];//定义数组装住车序号,以车数量为长度
for(int i=1;i<=get;i++)
{
System.out.println("请选择第 "+i+" 辆车的序号:");
cars[i-1] = scan.nextInt();//装序号
}
System.out.println("请选择使用天数:");
int time1 = scan.nextInt();
Arrays.sort(cars);
System.out.println("载客的有:");
int people = 0;//总人数
for(int i=0;i<get;i++)
{
System.out.print(car[cars[i]-1].check("h"));
people += car[cars[i]-1].people;
}
System.out.print(" 总载客量:"+ people);
System.out.println();
System.out.println("载重的有:");
int load = 0;//总重
for(int i=0;i<get;i++)
{
System.out.print(car[cars[i]-1].check("c"));
load += car[cars[i]-1].load;
}
System.out.println(" 总载重量:"+ load);
int money = 0;
for(int i=0;i<get;i++)
money+=car[cars[i]-1].price;
money*=time1;
System.out.println("总价钱:"+money);
}
}
}
最初在想主方法中,如何去确定我要的对象时,迷茫了一阵。之后看了书中用class类来做数组就可以轻松for循环对象,才点醒了我。
点击查看更多内容
4人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦