用java写出地铁计费系统
时间: 2023-11-20 20:07:18 浏览: 38
Java地铁计费系统源码.zip
5星 · 资源好评率100%
好的,地铁计费系统可以采用面向对象的思想来设计和实现。下面是一个简单的Java代码示例:
首先,我们需要定义一个地铁车站类和一个乘客类。
```java
public class Station {
private String name;
private double price;
public Station(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public class Passenger {
private double balance;
private Station startStation;
private Station endStation;
private double totalPrice;
public Passenger(double balance) {
this.balance = balance;
}
public void enterStation(Station station) {
startStation = station;
}
public void exitStation(Station station) {
endStation = station;
calculatePrice();
}
public void calculatePrice() {
double distance = Math.abs(startStation.getPrice() - endStation.getPrice());
totalPrice = distance * 2;
}
public void pay() {
if (balance >= totalPrice) {
balance -= totalPrice;
System.out.println("支付成功,余额:" + balance);
} else {
System.out.println("余额不足,请充值!");
}
}
}
```
然后,我们可以在主函数中创建一些站点和乘客对象,并模拟他们的进出站操作和支付操作。
```java
public static void main(String[] args) {
Station station1 = new Station("A", 1.0);
Station station2 = new Station("B", 2.0);
Station station3 = new Station("C", 3.0);
Passenger passenger = new Passenger(10.0);
passenger.enterStation(station1);
passenger.exitStation(station3);
passenger.pay();
}
```
这样,我们就完成了一个简单的地铁计费系统的设计和实现。当然,实际的地铁计费系统可能会更加复杂,需要考虑时间、距离、乘客类型等因素,以上代码仅供参考。
阅读全文