分别创建了三个类:车类、方法类、入口类。
Car.java
class Car {
private String name;
private int rent;
private int mannedNum;
private int goodsNum;
Car(String name, int rent, int mannedNum, int goodsNum) {
this.name = name;
this.rent = rent;
this.mannedNum = mannedNum;
this.goodsNum = goodsNum;
}
String getName() {
return name;
}
int getRent() {
return rent;
}
int getMannedNum() {
return mannedNum;
}
int getGoodsNum() {
return goodsNum;
}
@Override
public String toString() {
String str1 = mannedNum != 0 ? "载人:" + mannedNum + "人" + "\t" : "";
String str2 = goodsNum != 0 ? "载货:" + goodsNum + "吨" : "";
return name + "\t" + rent + "元/天\t\t" + str1 + str2;
}
}
Method.java
import java.util.Scanner;
class Method {
private static Scanner scan = new Scanner(System.in);
static Car[] list() {
Car[] cars = new Car[3];
cars[0] = new Car("奥迪A4", 500, 4, 0);
cars[1] = new Car("皮卡雪", 700, 4, 2);
cars[2] = new Car("松花江", 900, 0, 10);
System.out.println("序号\t名称\t\t租金\t\t\t容量");
for (int i = 0; i < cars.length; i++) {
System.out.println((i + 1) + "\t" + cars[i]);
}
return cars;
}
static int carNum() {
int carnum = 0;
for (; carnum <= 0 carnum >= 100; ) {
System.out.println("请输入你要租车的数量(1-99):");
carnum = scan.nextInt();
}
return carnum;
}
static void bill(Car[] cars, int num) {
int sum = 0;
int mannedNum = 0;
int goodsNum = 0;
String car = "";
String truck = "";
for (int i = 1; i <= num; i++) {
int j = -1;
for (; j < 0 j > cars.length - 1; ) {
System.out.println("请输入第" + i + "辆车的序号:");
j = (scan.nextInt() - 1);
}
sum += cars[j].getRent();
if (cars[j].getMannedNum() != 0) {
mannedNum += cars[j].getMannedNum();
car += cars[j].getName() + "\t";
}
if (cars[j].getGoodsNum() != 0) {
goodsNum += cars[j].getGoodsNum();
truck += cars[j].getName() + "\t";
}
}
int day = 0;
for (; day <= 0 day >= 100; ) {
System.out.println("请输入租车天数(1-99):");
day = scan.nextInt();
}
sum = sum * day;
System.out.println("————————————————————————\n你的账单:");
System.out.println("***共租了" + num + "辆车。");
System.out.println("***可载人的车有:");
System.out.println(car + " 可载人数:" + mannedNum + "人");
System.out.println("***可载货的车有:");
System.out.println(truck + " 可载货物:" + goodsNum + "吨");
System.out.println("***租车总价格:" + sum + "元\n——————————————————");
}
}
Initial.java
import java.util.Scanner;
public class Initial {
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("你是否要租车:1是 0否" + "\n请输入:");
int num = scan.nextInt();
for (; num != 1 && num != 0; ) {
System.out.println("输入有误,请重新输入:");
num = scan.nextInt();
}
if (num == 0) {
System.out.println("再见!");
} else {
System.out.println("欢迎使用,你可租车的类型及其价目表:");
//打印价目表,保存对象
Car[] cars = Method.list();
//获取租车数量,保存车数
int carnum = Method.carNum();
//获取租车细节并打印账单,传入对象和车数
Method.bill(cars, carnum);
System.out.println("完成租车!");
}
scan.close();
}
}