有這樣幾個時間段
從 至 收費
00:00~08:00 0元
08:00~10:00 5元
10:00~12:00 10元
12:00~15:00 15元
15:00~00:00 20元
顧客 9點開臺 13點結賬共消費3元
用Java實作,求演算法!
uj5u.com熱心網友回復:
題目要求不明確?08:00~10:00 5元 //這里的5元是每小時5元還是一共5元(也就是每小時2.5元)
另外,從你給的客戶消費情況和收費標準來推算,客戶一共玩了4個小時,怎么也算不出才收費3元,所以你的題目是不是還有什么條件沒說清楚?
uj5u.com熱心網友回復:

這個是原題
uj5u.com熱心網友回復:
好吧,這其實涉及不到演算法,就是回圈時間取每個計費區間的費用累加即可,純體力勞動,就給你寫個小例子吧因為題目的邊界條件不是很明確(具體看代碼中的測驗資料),所以如果邊界條件有出入,請自行修改代碼
整個代碼核心的部分只有幾個地方(代碼注釋中用【重點】標識)
class PriceUnit { //單價類(考慮到單價的單位不同,有按小時的,有按分鐘,所以特別做了個單價類以進行單價換算)
private double price;
private int unit; //0:hore, 1:minute
PriceUnit(double price, int unit) {
this.price = price;
this.unit = unit;
}
public double getPrice() {return price;}
public void setPrice(double price) {this.price = price;}
public int getUnit() {return unit;}
public void setUnit(int unit) {this.unit = unit;}
public String toString() {
return String.format("%.0f/%s", price, (unit==0 ? "小時" : "分鐘"));
}
public PriceUnit convertUnit(int toUnit) { //單價換算
switch(toUnit) {
case 0:
switch(this.unit) {
case 1:
this.price *= 60;
break;
}
break;
case 1:
switch(this.unit) {
case 0:
this.price /= 60;
break;
}
break;
}
this.unit = toUnit;
return this;
}
}
class ParkPrice extends PriceUnit { //停車時間區間單價類
private int start;
private int end;
public ParkPrice(int start, int end, double price) {
this(start, end, price, 0);
}
public ParkPrice(int start, int end, double price, int unit) {
super(price, unit);
this.start = start;
this.end = end;
}
public int getStart() {return start;}
public int getEnd() {return end;}
public String toString() {
return String.format("%02d:00~%02d:00 %s", start, end, super.toString());
}
public ParkPrice convertUnit(int toUnit) {
super.convertUnit(toUnit);
return this;
}
}
public class ParkFeeSimulator { //模擬停車計費主類
private static ParkPrice parkPrice[] = { //【重點1】:構造一個時間段的價格表陣列
new ParkPrice(0, 5, 2),
new ParkPrice(5, 7, 10),
new ParkPrice(7, 12, 6),
new ParkPrice(12, 14, 10),
new ParkPrice(14, 18, 2),
new ParkPrice(18, 19, 1, 1).convertUnit(0), //這個需求不明確,題目要求不足1小時按小時收費,所以統一轉成小時單價
new ParkPrice(19, 21, 20),
new ParkPrice(21, 24, 6)
};
private int freeMinute; //免費時間
private double maxFeePreDay; //1日最大費用
public ParkFeeSimulator(int freeMinute, double maxFeePreDay) {
this.freeMinute = freeMinute;
this.maxFeePreDay = maxFeePreDay;
}
public void setFreeMinute(int freeMinute) { //根據題目要求這個可變
this.freeMinute = freeMinute;
}
public void setMaxFeereDay(double maxFeePreDay) { //根據題目要求這個可變
this.maxFeePreDay = maxFeePreDay;
}
public void listParkPrice() { //列印收費表
System.out.printf("停車收費價格表\n");
for (int i=0; i<parkPrice.length; i++) {
System.out.printf("%d %s\n", i+1, parkPrice[i]);
}
}
protected double getParkPrice(int hour) { //【重點2】:通過時間引數從價格表陣列查找并取得相應的時區價格
for (ParkPrice pp : parkPrice) {
if (hour > pp.getStart() && hour <= pp.getEnd()) {
return pp.getPrice();
}
}
return 0;
}
public double caculatePartFee(Calendar start, Calendar end) { //根據開始時間,停止時間計費(核心代碼)
double fee = 0.0;
int days = 0, hour = 0;
start.add(Calendar.MINUTE, freeMinute); //開始時間修正(加上免費時間)
if (!start.before(end)) { //如果在免費區間
return fee;
}
for (; start.before(end); start.add(Calendar.DATE, 1)) { //【重點3】:算出滿整天的日數
days++;
}
if (start.after(end)) { //【重點4】:如果算出跨天后的時間大于結束時間,則說明最后一次跨天計算不滿一天
start.add(Calendar.DATE, -1); //所以要回退一天,按小時來計算
days--;
hour = start.get(Calendar.HOUR_OF_DAY); //取出開始時間
if (start.get(Calendar.MINUTE) == 0
&& start.get(Calendar.SECOND) == 0
&& start.get(Calendar.MILLISECOND) == 0) { //如果開始時間剛為整點小時數
hour++; //則修正計費基準為下一小時(因為計時區間是(開始時間,結束時間],不包含整點的開始時間,所以修正為下一小時,確保在計時區間內)
} else { //否則修正時間為整點小時數
start.add(Calendar.HOUR, 1); //即把小時進位
start.set(Calendar.MINUTE, 0); //分鐘以下清0
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
}
fee += getParkPrice(hour); //【重點5】:計算第1小時的費用(放在這里計算是為了避免不滿1小時而不進入for回圈的情況)
start.add(Calendar.HOUR, 1); //計費后時間累加1小時
for (; !start.after(end); start.add(Calendar.HOUR, 1)) { //【重點6】:回圈時間,累加每小時的費用
hour = start.get(Calendar.HOUR_OF_DAY);
fee += getParkPrice(hour); //【重點7】:如果收費編號6按分鐘收費,可以改善這里
}
}
fee += days * maxFeePreDay; //【重點8】:最后加上滿1整天的最大停車費用
return fee;
}
public static void main(String[] args) {
try {
ParkFeeSimulator ps = new ParkFeeSimulator(15, 120);
ps.listParkPrice();
System.out.printf("模擬停車小例子\n");
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
/*
// 從控制臺輸入資料的情況
Scanner sc = new Scanner(System.in);
System.out.printf("請輸入開始時間(格式: yyyyMMddHHmmss):");
String str = sc.nextLine();
c1.setTime(sdf.parse(str));
System.out.printf("請輸入結束時間(格式: yyyyMMddHHmmss):");
str = sc.nextLine();
c2.setTime(sdf.parse(str));
*/
String[][] testData = { //測驗資料
{"20200401100001", "20200403180000"},
{"20200401110001", "20200401120000"},
{"20200401114501", "20200401120001"},//這個邊界資料,這個算不算免費區間?
{"20200401114500", "20200401120001"},//還是這個才算免費區間?根據需求自行修改caculatePartFee方法
{"20200331234501", "20200401240000"},//這兩個邊界資料,這個算不算24小時滿1整天?
{"20200331234500", "20200401240000"} //還是這個才算24小時滿一整天?根據需求自行修改caculatePartFee方法
};
for (int i=0; i<testData.length; i++) {
c1.setTime(sdf.parse(testData[i][0]));
c2.setTime(sdf.parse(testData[i][1]));
System.out.printf("開始時間: %tF %tT\n結束時間: %tF %tT\n", c1.getTime(), c1.getTime(), c2.getTime(), c2.getTime());
System.out.printf("總停車費: %.0f\n", ps.caculatePartFee(c1, c2));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}uj5u.com熱心網友回復:
三樓的代碼的 3.功能實作類CountCost.java有點BUG,以本樓的代碼為準!還是按順序來操作吧,注意包名哈!
1.定義一個物體類
package com.paullbm.timingcost.entity;
/**
* @author paullbm
*/
public class PriceItem {
private int no;
private int start;
private int end;
private int price;
public PriceItem(int no, int start, int end, int price) {
this.no = no;
this.start = start;
this.end = end;
this.price = price;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append("no=").append(no);
sb.append(",start=").append(start);
sb.append(",end=").append(end);
sb.append(",price=").append(price);
sb.append("]");
return sb.toString();
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public int getPrice() {
return price;
}
}
2.定義一個介面
package com.paullbm.timingcost;
/**
* @author paullbm
*/
public interface ICountCost {
//獲取總價
public int getTotalPrice();
}
3.定義一個功能實作類
package com.paullbm.timingcost.impl;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.paullbm.timingcost.ICountCost;
import com.paullbm.timingcost.entity.PriceItem;
/**
* @author paullbm
*/
public class CountCost implements ICountCost {
private int freeTimeSecond = 15 * 60; // 15分鐘免費時間(秒數)
private int oneDayLimitCost = 120; // 1天的封頂費用
private int oneHourSecond = 60 * 60; // 1小時包含的秒數
private long oneDaySecond = 24 * oneHourSecond; // =86400秒
private long east8ZoneSecond = 8 * oneHourSecond; // 東八區附加秒數
private int[][] listPrices = {
{ 1, 0, 5, 2 },
{ 2, 5, 7, 10 },
{ 3, 7, 12, 6 },
{ 4, 12, 14, 10 },
{ 5, 14, 18, 2 },
{ 6, 18, 19, 1 },
{ 7, 19, 21, 20 },
{ 8, 21, 24, 6 }
};
private String fmtDateStr="yyyy-MM-dd HH:mm:ss";
private ArrayList<PriceItem> itemList = new ArrayList<PriceItem>();
private Date startDate;
private Date endDate;
public CountCost(String startTime, String endTime) {
Date startDate = null;
Date endDate = null;
SimpleDateFormat simdate = new SimpleDateFormat(this.fmtDateStr);
try {
startDate = simdate.parse(startTime);
endDate = simdate.parse(endTime);
} catch (ParseException e) {
e.printStackTrace();
}
this.init(startDate, endDate);
}
public CountCost(Date startDate, Date endDate) {
this.init(startDate, endDate);
}
private void init(Date startDate, Date endDate) {
this.startDate = startDate;
this.endDate = endDate;
for (int i = 0; i < 8; i++) {
PriceItem struct = new PriceItem(
this.listPrices[i][0],
this.listPrices[i][1] * this.oneHourSecond,
this.listPrices[i][2] * this.oneHourSecond,
this.listPrices[i][3]);
this.itemList.add(i, struct);
}
}
@Override
public int getTotalPrice() {
long startTimeSecond = this.startDate.getTime() / 1000;
long endTimeSecond = this.endDate.getTime() / 1000;
if (isFreeTime(startTimeSecond, endTimeSecond)) // 如果是免費時間內
return 0;
int totalPrice = 0;
int limitCost=getLimitCost(startTimeSecond, endTimeSecond);
int normalCost = getWithin1DayCost(startTimeSecond, endTimeSecond);
totalPrice += (limitCost+normalCost);
System.out.println("封頂消費="+limitCost + "元");
System.out.println("普通消費="+normalCost + "元");
return totalPrice;
}
// 判斷是否是在免費時間范圍內
private boolean isFreeTime(long startTimeSecond, long endTimeSecond) {
long timeDiff = endTimeSecond - startTimeSecond;
if (timeDiff <= freeTimeSecond)
return true;
return false;
}
// 計算封頂費用
private int getLimitCost(long startTimeSecond, long endTimeSecond) {
int limitPrice = 0;
while (true) {
if (endTimeSecond - startTimeSecond >= oneDaySecond) {
limitPrice += oneDayLimitCost;
startTimeSecond += oneDaySecond;
} else {
break;
}
}
return limitPrice;
}
//計算1天以內的小時數的消費金額(要注意跨天問題)
private int getWithin1DayCost(long startTimeSecond, long endTimeSecond) {
int normalPrice = 0;
long relativeStartTimeSecond = (startTimeSecond + east8ZoneSecond) % oneDaySecond
+ freeTimeSecond; //東八區調整再累加免費時長
long relativeEndTimeSecond = (endTimeSecond + east8ZoneSecond) % oneDaySecond;
if (relativeEndTimeSecond < relativeStartTimeSecond) {
//考慮跨天問題,相對結束時間則需要累加1天
relativeEndTimeSecond += oneDaySecond;
}
long offsetTimeSecond = oneHourSecond - (relativeStartTimeSecond % oneHourSecond) + 1; // 計算時間偏移量
boolean isFirst = true;
int index = 0;
int size=itemList.size();
while (relativeStartTimeSecond < relativeEndTimeSecond) {
while(index < size) {
if(relativeStartTimeSecond >= relativeEndTimeSecond)
break;
PriceItem item = itemList.get(index);
if (relativeStartTimeSecond > item.getStart()
&& relativeStartTimeSecond < item.getEnd()) {
normalPrice += item.getPrice();
if (isFirst) { // 首次要添加時間偏移量
relativeStartTimeSecond += offsetTimeSecond;
isFirst = false;
} else { // 之后可進行整小時添加
relativeStartTimeSecond += oneHourSecond;
}
System.out.print(item + ", 階段性累計消費=" + normalPrice + "元\n");
// System.out.println(", relativeStartTimeSecond=" + relativeStartTimeSecond
// + ", relativeEndTimeSecond=" + relativeEndTimeSecond);
}else{
if(relativeStartTimeSecond > item.getEnd())
index++;
}
}
if (relativeEndTimeSecond > oneDaySecond) {
//如果按條件迭代完this.itemList還能進入此處
//說明存在跨天情況,則需要進行相關調整
relativeStartTimeSecond = 1;
relativeEndTimeSecond -= oneDaySecond;
index = 0;
}
}
return normalPrice;
}
}
4.測驗類
package com.paullbm.timingcost.test;
import com.paullbm.timingcost.ICountCost;
import com.paullbm.timingcost.impl.CountCost;
/**
* @author paullbm
*/
public class CountCostTest {
public static void main(String[] args) {
String startTime = "2020-04-01 18:00:01";
String endTime = "2020-04-03 10:00:00";
// String startTime = "2020-04-01 10:15:01";
// String endTime = "2020-04-01 17:00:02";
ICountCost cc = new CountCost(startTime, endTime);
int totalPrice = cc.getTotalPrice();
System.out.println("總消費金額=" + totalPrice+ "元");
}
}
uj5u.com熱心網友回復:
這道題看似不難,其實里面暗藏了很多需要注意的地方。我的程式注釋非常清楚,請看程式吧FareRule.java 計費規則類及設定計費規則類
package 停車場計費;
//FareRule是計費時段的計費規則的類
public class FareRule {
private int begin; //計費段起始小時
private int end; //計費段結束小時
private int unitPrice; //計費單價
int minute;//0:按小時計費;1:按分鐘計費;2:表示該計費規則結束且本條規則也無效
public FareRule() {
}
public FareRule(int begin, int end, int unitPrice, int minute) {
this.begin = begin;
this.end = end;
this.unitPrice = unitPrice;
this.minute = minute;
}
public int getBegin() {
return begin;
}
public void setBegin(int begin) {
this.begin = begin;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
public int isMinute() {
return minute;
}
public void setMinute(int minute) {
this.minute = minute;
}
}
//SetFareRule是設定計費規則的類,根據你的題目要求:“時間段計費規則可能調整”
class SetFareRule {//設定規則
static FareRule[] rules = {//題目要求的計費規則
new FareRule(0, 5, 2, 0),
new FareRule(5, 7, 10, 0),
new FareRule(7, 12, 6, 0),
new FareRule(12, 14, 10, 0),
new FareRule(14, 18, 2, 0),
new FareRule(18, 19, 1, 1),
new FareRule(19, 21, 20, 0),
new FareRule(21, 24, 6, 0),
new FareRule(0,0,0,3),
};
public static void setRule(FareRule rule,int index) {//用于修改1條規則
rules[index] = rule;
}
//默認設定,一天24小時,每小時一個時段,清零為下面設定規則準備容器。
public void setRules() {
rules = new FareRule[24];
for(int i=0;i<24;i++) {
rules[i] = new FareRule();
}
}
//修改多條規則
public static void setRules(FareRule[] rs,int beginIdex,int num) {
for(int i=0;i<num;i++) {
rules[beginIdex+i]=rs[i];
}
}
public static void showPriceList() { //列印收費表
System.out.printf("停車收費價格表\n");
for (int i=0; i<rules.length; i++) {
if(rules[i].minute==1)
System.out.printf("%d\t%d點——%d點%d元/分鐘\n",
i+1, rules[i].getBegin(),rules[i].getEnd(),
rules[i].getUnitPrice());
else System.out.printf("%d\t%d點——%d點%d元/小時\n",
i+1, rules[i].getBegin(),rules[i].getEnd(),
rules[i].getUnitPrice());
}
}
}
Fare.java:計費類
// Fare是計費類
//停車場計費:計費起始時間=(入場時間-免費時間)
//停車超過1年則:計費天數=年數*365;
//(剩余)不滿1年:計費天數+=(剩余)天數;
//(剩余)不滿24小時,則按時段進行計費。
package 停車場計費;
import java.util.Calendar;
public class Fare {
Calendar enterTime; //入場時間
Calendar begin = Calendar.getInstance();//階段起始時間
Calendar fareBegin; //計費起始時間
Calendar now = Calendar.getInstance();//汽車出場時間取當前時間
private int freeMinute; //免費時間
private double maxFarePreDay; //1日最大費用
public Fare(int freeMinute, double maxFarePreDay) {
this.freeMinute = freeMinute;
this.maxFarePreDay = maxFarePreDay;
}
public Calendar getEnterTime() {
return enterTime;
}
public void setEnterTime(Calendar enterTime) {
this.enterTime = enterTime;
}
public int getFreeMinute() {
return freeMinute;
}
public void setFreeMinute(int freeMinute) { //根據題目要求這個可變
this.freeMinute = freeMinute;
}
public double getMaxFarePreDay() {
return maxFarePreDay;
}
public void setMaxFareDay(double maxFarePreDay) { //根據題目要求這個可變
this.maxFarePreDay = maxFarePreDay;
}
public void listParkPrice() { //列印收費表
System.out.printf("停車收費價格表\n");
for (int i=0; i<SetFareRule.rules.length; i++) {
if(SetFareRule.rules[i].minute==2) break;
System.out.printf("%d %s\n", i+1, SetFareRule.rules[i]);
}
}
Calendar getBegin() {//獲取計費起始時間=入場時間+免費時間
fareBegin = Calendar.getInstance();
fareBegin.setTimeInMillis(enterTime.getTimeInMillis()+freeMinute*60*1000);
return fareBegin;
}
protected double getPrice() {//計費
int day=0; //停車天數
int year=0; //停車年數
double price=0;
/*下面是準備作業*/
getBegin(); //獲取計費起始時間
fareBegin.set(Calendar.SECOND,0); //秒不計費,所以計費起始清零
now.set(Calendar.SECOND,0); //出場時間秒也清零
begin.setTimeInMillis(fareBegin.getTimeInMillis()); //初始化階段計費起始時間
if(begin.getTimeInMillis()>now.getTimeInMillis())
return price; //如果在免費時間段內則收費為0
year=(now.get(Calendar.YEAR) - begin.get(Calendar.YEAR));
if(year>0) {//如果停車超過1年,則停車天數+=年數*365
day = year * 365;
begin.set(Calendar.YEAR,begin.get(Calendar.YEAR)+year);
}
//如果停車未超過1年,則停車天數+=天數
day+=now.get(Calendar.DAY_OF_YEAR)-begin.get(Calendar.DAY_OF_YEAR);
price+=day*maxFarePreDay; //計算按天收費的收費值
//下面是通過查詢計費時段規則表(陣列)按時段計算收費值
for (FareRule rule : SetFareRule.rules) {
switch (rule.minute) {
case 0: //按小時計費
if (begin.get(Calendar.HOUR_OF_DAY) >= rule.getBegin() &&
begin.get(Calendar.HOUR_OF_DAY) <= rule.getEnd()) {
if(now.get(Calendar.HOUR_OF_DAY)>=rule.getEnd())
price += (rule.getEnd()-begin.get(Calendar.HOUR_OF_DAY)) * rule.getUnitPrice();
else if(begin.get(Calendar.MINUTE)==now.get(Calendar.MINUTE))
price+= (now.get(Calendar.HOUR_OF_DAY)-begin.get(Calendar.HOUR_OF_DAY))*rule.getUnitPrice();
else
price+= (now.get(Calendar.HOUR_OF_DAY)-begin.get(Calendar.HOUR_OF_DAY)+1)*rule.getUnitPrice();
begin.set(Calendar.HOUR_OF_DAY,rule.getEnd());
}
break;
case 1: //按分鐘計費
if (begin.get(Calendar.HOUR_OF_DAY) >= rule.getBegin() &&
begin.get(Calendar.HOUR_OF_DAY) <= rule.getEnd()) {
if (begin.getTimeInMillis() != fareBegin.getTimeInMillis())
begin.set(Calendar.MINUTE, 0); //將begin分鐘清零
if (now.get(Calendar.HOUR_OF_DAY) >= rule.getEnd())
price += rule.getUnitPrice() * (rule.getEnd() - rule.getBegin()) * 60;
else price += (now.get(Calendar.MINUTE) - begin.get(Calendar.MINUTE)) * rule.getUnitPrice();
begin.set(Calendar.HOUR_OF_DAY, rule.getEnd()); //更新階段計費起始時間
begin.set(Calendar.MINUTE, 0); //已經按分鐘計費了,則分鐘數清零
}
break;
}
if(begin.getTimeInMillis()>=now.getTimeInMillis()) break;//計費完成
}
return price;
}
}
ParkFare.java 應用源檔案
package 停車場計費;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class ParkFare {//模擬停車計費主類
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//新進場了一輛車
Fare car = new Fare(15,120.0);
SetFareRule.showPriceList(); //輸出停車場收費價目表
try {
System.out.printf("模擬停車\n");
Calendar c1 = Calendar.getInstance();
String[] testData = { //測驗資料,汽車入場時間
"20200411184501", "20200411180000",
"20200412151501", "20200412190000",
"20200411114501", "20200411100001",
"20200411114500", "20200411120001",
"20200410234501", "20200411240000",
"20200411214500", "20200411220000"};
for (int i=0; i<testData.length; i++) {
c1.setTime(sdf.parse(testData[i]));
car.setEnterTime(c1); //設定汽車入場時間
System.out.printf("開始時間: %tF %tT\n結束時間: %tF %tT\n",
c1.getTime(), c1.getTime(), car.now.getTime(), car.now.getTime());
System.out.printf("總停車費: %.0f\n", car.getPrice());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
uj5u.com熱心網友回復:
運行結果:停車收費價格表
1 0點——5點2元/小時
2 5點——7點10元/小時
3 7點——12點6元/小時
4 12點——14點10元/小時
5 14點——18點2元/小時
6 18點——19點1元/分鐘
7 19點——21點20元/小時
8 21點——24點6元/小時
9 0點——0點0元/小時
模擬停車
開始時間: 2020-04-11 18:45:01
結束時間: 2020-04-12 00:23:58
總停車費: -337
開始時間: 2020-04-11 18:00:00
結束時間: 2020-04-12 00:23:00
總停車費: -386
開始時間: 2020-04-12 15:15:01
結束時間: 2020-04-12 00:23:00
總停車費: 0
開始時間: 2020-04-12 19:00:00
結束時間: 2020-04-12 00:23:00
總停車費: 0
開始時間: 2020-04-11 11:45:01
結束時間: 2020-04-12 00:23:00
總停車費: -539
開始時間: 2020-04-11 10:00:01
結束時間: 2020-04-12 00:23:00
總停車費: -527
開始時間: 2020-04-11 11:45:00
結束時間: 2020-04-12 00:23:00
總停車費: -539
開始時間: 2020-04-11 12:00:01
結束時間: 2020-04-12 00:23:00
總停車費: -539
開始時間: 2020-04-10 23:45:01
結束時間: 2020-04-12 00:23:00
總停車費: -547
開始時間: 2020-04-12 00:00:00
結束時間: 2020-04-12 00:23:00
總停車費: 2
開始時間: 2020-04-11 21:45:00
結束時間: 2020-04-12 00:23:00
總停車費: -6
開始時間: 2020-04-11 22:00:00
結束時間: 2020-04-12 00:23:00
總停車費: -6
Process finished with exit code 0
uj5u.com熱心網友回復:
昨天發的貼子程式有問題,沒有考慮到跨0點的情況,后來想到一個解題方法:把24小時內計費規則細化為24個時段,每小時一個計費時段。然后計費從入場的小時為起點:回圈根據計費規則進行計費,一直到出場為止。利用[i%rules.length解決了回環(跨0點)問題for (int i=fareBegin.get(Calendar.HOUR_OF_DAY);i<(rules.length+fareBegin.get(Calendar.HOUR_OF_DAY));i++) {
rules[i%rules.length] //這樣解決了回環(跨0點)問題
}
這樣終于對于很多測驗用例得結果都正確了。
FareRule.java包括:FareRule類:計費規則類;SetFareRule類:設定計費規則類
import exception.IndexException;
// FareRule是計費時段的計費規則的類
public class FareRule {
public static final int MINUTE=1;
private int begin; //計費段起始小時
private int end; //計費段結束小時
private int unitPrice; //計費單價
int minute;//0:按小時計費;1:按分鐘計費。
public FareRule() {
}
public FareRule(int begin, int end, int unitPrice, int minute) {
this.begin = begin;
this.end = end;
this.unitPrice = unitPrice;
this.minute = minute;
}
public int getBegin() {
return begin;
}
public void setBegin(int begin) {
this.begin = begin;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public int getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(int unitPrice) {
this.unitPrice = unitPrice;
}
public boolean isMinute() {
if(minute==MINUTE) return true;
return false;
}
public void setMinute(int minute) {
this.minute = minute;
}
}
// SetFareRule是設定計費規則的類,根據你的題目要求:“時間段計費規則可能調整”
class SetFareRule {//設定規則
public static final int INIRULE=0;
public static final int RULE=1;
//題目要求的計費規則,為初始規則表,為了程式便于處理,將被轉換為按每小時分段規則:rules[]
static FareRule[] iniRules = {
new FareRule(0, 5, 2, 0),
new FareRule(5, 7, 10, 0),
new FareRule(7, 12, 6, 0),
new FareRule(12, 14, 10, 0),
new FareRule(14, 18, 2, 0),
new FareRule(18, 19, 1, 1),
new FareRule(19, 21, 20, 0),
new FareRule(21, 24, 6, 0),
};
//每小時分段計費規則表
static FareRule[] rules;
public static void setRule(FareRule rule,int index) {//用于修改1條規則
rules[index] = rule;
}
//默認設定,一天24小時,每小時一個時段,清零為下面設定規則準備容器。
public static void setRules(int num) {
rules = new FareRule[num];
for(int i=0;i<num;i++) {
rules[i] = new FareRule();
}
}
//初始化規則表rules[]
public static void iniRules(){
setRules(24);
for(FareRule rule: iniRules) {
for(int i=rule.getBegin();i<rule.getEnd();i++) {
rules[i].setBegin(i);
rules[i].setEnd(i+1);
rules[i].setUnitPrice(rule.getUnitPrice());
rules[i].minute = rule.minute;
}
}
}
//修改多條規則
public static void setRules(FareRule[] rs,int beginIdex,int num,int rsType) throws IndexException{
if(beginIdex<0) throw new IndexException(beginIdex);
if (rsType==INIRULE) {
for (int i = 0; i < num; i++) {
iniRules[beginIdex + i] = rs[i];
}
} else {
for (int i = 0; i < num; i++) {
rules[beginIdex + i] = rs[i];
}
}
}
public static void showPriceList() { //列印收費表
System.out.printf("停車收費價格表\n");
for (int i=0; i<rules.length; i++) {
if(rules[i].minute==1)
System.out.printf("%d\t%d點——%d點%d元/分鐘\n",
i+1, rules[i].getBegin(),rules[i].getEnd(),
rules[i].getUnitPrice());
else System.out.printf("%d\t%d點——%d點%d元/小時\n",
i+1, rules[i].getBegin(),rules[i].getEnd(),
rules[i].getUnitPrice());
}
}
}
Fare.java是Fare類:計費類的源檔案
//Fare是計費類
//停車場計費:計費起始時間=(入場時間-免費時間)
//停車超過1年則:計費天數=年數*365;
//(剩余)不滿1年:計費天數+=(剩余)天數;
//(剩余)不滿24小時,則按時段進行計費。
import java.util.Calendar;
public class Fare {
Calendar enterTime; //入場時間
Calendar begin = Calendar.getInstance();//時段起始時間
Calendar fareBegin; //計費起始時間
Calendar now = Calendar.getInstance();//汽車出場時間取當前時間
private int freeMinute; //免費時間
private double maxFarePreDay; //1日最大費用
public Fare(int freeMinute, double maxFarePreDay) {
this.freeMinute = freeMinute;
this.maxFarePreDay = maxFarePreDay;
}
public Calendar getEnterTime() {
return enterTime;
}
public void setEnterTime(Calendar enterTime) {
this.enterTime = enterTime;
}
public int getFreeMinute() {
return freeMinute;
}
public void setFreeMinute(int freeMinute) { //根據題目要求這個可變
this.freeMinute = freeMinute;
}
public double getMaxFarePreDay() {
return maxFarePreDay;
}
public void setMaxFareDay(double maxFarePreDay) { //根據題目要求這個可變
this.maxFarePreDay = maxFarePreDay;
}
public void listParkPrice() { //列印收費表
System.out.printf("停車收費價格表\n");
for (int i=0; i<SetFareRule.rules.length; i++) {
if(SetFareRule.rules[i].minute==2) break;
System.out.printf("%d %s\n", i+1, SetFareRule.rules[i]);
}
}
Calendar getBegin() {//獲取計費起始時間=入場時間+免費時間
fareBegin = Calendar.getInstance();
fareBegin.setTimeInMillis(enterTime.getTimeInMillis()+freeMinute*60*1000);
return fareBegin;
}
protected double getPrice() {//計費
int day=0; //停車天數
int year=0; //停車年數
double price=0; //總停車費
double price24=0; //(剩余)不滿24小時停車費,如果該費用超過日封頂停車費,則計封頂停車費
/*下面是準備作業*/
getBegin(); //獲取計費起始時間
now.set(Calendar.SECOND,0); //出場時間秒也清零
if(fareBegin.getTimeInMillis()>now.getTimeInMillis())
return price; //如果在免費時間段內則收費為0
year=(now.get(Calendar.YEAR) - fareBegin.get(Calendar.YEAR));
if(year>0) {//如果停車超過1年,則停車天數+=年數*365
day = year * 365;
fareBegin.set(Calendar.YEAR,fareBegin.get(Calendar.YEAR)+year);
}
//如果停車未超過1年,則停車天數+=天數
day+=now.get(Calendar.DAY_OF_YEAR)-fareBegin.get(Calendar.DAY_OF_YEAR);
//時間需要考慮跨0點的情況
if(fareBegin.get(Calendar.HOUR_OF_DAY)>now.get(Calendar.HOUR_OF_DAY)) day--;
price+=day*maxFarePreDay; //計算按天收費的收費值
//下面是通過查詢計費時段規則表(陣列)按時段計算收費值
FareRule[] rules = SetFareRule.rules; //宣告一個區域變數指向計費規則表
begin.setTimeInMillis(fareBegin.getTimeInMillis()); //初始化時段計費起始時間
for (int i=fareBegin.get(Calendar.HOUR_OF_DAY);i<(rules.length+fareBegin.get(Calendar.HOUR_OF_DAY));i++) {
//利用i%rules.length解決了回環(跨0點)問題
switch (rules[i%rules.length].minute) {
case 0: //按小時計費
price24 += rules[i%rules.length].getUnitPrice();
//跟新計費起始時段
begin.set(Calendar.HOUR_OF_DAY, begin.get(Calendar.HOUR_OF_DAY) + 1);
break;
case 1: //按分鐘計費
if (begin.get(Calendar.HOUR_OF_DAY) == rules[i%rules.length].getBegin()) {
if (now.get(Calendar.HOUR_OF_DAY) >= rules[i%rules.length].getEnd()) {
price24 += rules[i%rules.length].getUnitPrice() * 60;
//跟新計費起始時段
begin.set(Calendar.HOUR_OF_DAY,begin.get(Calendar.HOUR_OF_DAY)+1);
}
else {
price24 += now.get(Calendar.MINUTE) * rules[i%rules.length].getUnitPrice();
begin.setTimeInMillis(now.getTimeInMillis());
}
}
break;
}
if(begin.getTimeInMillis()>=now.getTimeInMillis()) break;//計費完成
}
if(price24>maxFarePreDay) price+=maxFarePreDay;
else price+=price24;
return price;
}
}
ParkFare.java檔案包括:ParkFare類,這個是計費應用(測驗)類
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class ParkFare {//模擬停車計費主類
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//新進場了一輛車
Fare car = new Fare(15,120.0);
SetFareRule.iniRules(); //初始化規則表
//SetFareRule.showPriceList(); //輸出停車場收費價目表
try {
System.out.printf("模擬停車\n");
Calendar c1 = Calendar.getInstance();
String[] testData = { //測驗資料,汽車入場時間
"20200412124501", "2020041220000",
"20200412151501", "20200412190000",
"20200412114501", "20200412100001",
"20200412164500", "20200412120001",
"20200410234501", "20200412240000",
"20200412211500", "20200412203000"};
for (int i=0; i<testData.length; i++) {
c1.setTime(sdf.parse(testData[i]));
car.setEnterTime(c1); //設定汽車入場時間
System.out.printf("開始時間: %tF %tT\t結束時間: %tF %tT\t",
c1.getTime(), c1.getTime(), car.now.getTime(), car.now.getTime());
System.out.printf("總停車費: %.0f\n", car.getPrice());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/93187.html
標籤:Java SE
