用Java代码多线程,集合,网络通信,GUI,IO,写一个租车App
时间: 2023-07-16 19:13:58 浏览: 48
好的,下面是一个简单的租车App的Java代码示例,它包含多线程、集合、网络通信、GUI和IO等功能。
1. 首先创建一个Car类,表示汽车:
```java
public class Car {
private String id; // 汽车编号
private String name; // 汽车名称
private String type; // 汽车类型
private double price; // 汽车租金
private boolean isRented; // 汽车是否已经租出
public Car(String id, String name, String type, double price) {
this.id = id;
this.name = name;
this.type = type;
this.price = price;
this.isRented = false;
}
// getter和setter方法
// ...
}
```
2. 然后创建一个CarRentalSystem类,表示租车系统,其中包含了所有可租的汽车,以及租车和还车的功能:
```java
import java.util.ArrayList;
import java.util.List;
public class CarRentalSystem {
private List<Car> cars; // 所有可租的汽车列表
public CarRentalSystem() {
this.cars = new ArrayList<>();
// 初始化所有可租的汽车
cars.add(new Car("001", "奔驰", "豪华车", 500.0));
cars.add(new Car("002", "宝马", "豪华车", 450.0));
cars.add(new Car("003", "别克", "商务车", 300.0));
cars.add(new Car("004", "雪佛兰", "家庭车", 200.0));
cars.add(new Car("005", "丰田", "家庭车", 180.0));
}
// 获取所有可租的汽车列表
public List<Car> getCars() {
return cars;
}
// 根据编号查找汽车
public Car findCarById(String id) {
for (Car car : cars) {
if (car.getId().equals(id)) {
return car;
}
}
return null;
}
// 租车
public synchronized boolean rentCar(String id) {
Car car = findCarById(id);
if (car != null && !car.isRented()) {
car.setRented(true);
return true;
}
return false;
}
// 还车
public synchronized boolean returnCar(String id) {
Car car = findCarById(id);
if (car != null && car.isRented()) {
car.setRented(false);
return true;
}
return false;
}
}
```
3. 接下来创建一个客户端界面,包含租车和还车的操作:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
public class CarRentalClient extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextArea taInfo; // 显示租车信息
private JButton btnRent; // 租车按钮
private JButton btnReturn; // 还车按钮
private JComboBox<String> cbCars; // 可租的汽车列表
private CarRentalSystem rentalSystem; // 租车系统
private Socket socket; // 与服务器连接的套接字
private BufferedReader reader; // 从服务器读取数据的输入流
private PrintWriter writer; // 向服务器发送数据的输出流
public CarRentalClient() {
setTitle("租车系统客户端");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 600, 400);
setLayout(new BorderLayout());
taInfo = new JTextArea();
add(new JScrollPane(taInfo), BorderLayout.CENTER);
JPanel panel = new JPanel();
add(panel, BorderLayout.SOUTH);
rentalSystem = new CarRentalSystem();
List<Car> cars = rentalSystem.getCars();
String[] carNames = new String[cars.size()];
for (int i = 0; i < cars.size(); i++) {
carNames[i] = cars.get(i).getName() + " (" + cars.get(i).getId() + ")";
}
cbCars = new JComboBox<>(carNames);
panel.add(cbCars);
btnRent = new JButton("租车");
btnRent.addActionListener(this);
panel.add(btnRent);
btnReturn = new JButton("还车");
btnReturn.addActionListener(this);
panel.add(btnReturn);
setVisible(true);
connectToServer();
}
// 连接到服务器
private void connectToServer() {
try {
socket = new Socket("localhost", 8888);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
new Thread(new ServerListener()).start();
} catch (Exception e) {
taInfo.append("连接服务器失败:" + e.getMessage() + "\n");
}
}
// 处理按钮事件
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnRent) {
String carId = rentalSystem.getCars().get(cbCars.getSelectedIndex()).getId();
writer.println("rent," + carId);
} else if (e.getSource() == btnReturn) {
String carId = rentalSystem.getCars().get(cbCars.getSelectedIndex()).getId();
writer.println("return," + carId);
}
}
// 从服务器读取信息的线程
private class ServerListener implements Runnable {
@Override
public void run() {
try {
while (true) {
String msg = reader.readLine();
if (msg != null) {
String[] parts = msg.split(",");
if (parts.length == 2) {
String action = parts[0];
String carId = parts[1];
if (action.equals("rent")) {
boolean success = rentalSystem.rentCar(carId);
if (success) {
taInfo.append("租车成功!\n");
} else {
taInfo.append("租车失败!\n");
}
} else if (action.equals("return")) {
boolean success = rentalSystem.returnCar(carId);
if (success) {
taInfo.append("还车成功!\n");
} else {
taInfo.append("还车失败!\n");
}
}
}
}
}
} catch (Exception e) {
taInfo.append("与服务器连接断开:" + e.getMessage() + "\n");
}
}
}
public static void main(String[] args) {
new CarRentalClient();
}
}
```
4. 最后创建一个服务器程序,处理租车和还车的请求:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class CarRentalServer {
private static CarRentalSystem rentalSystem = new CarRentalSystem();
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
System.out.println("服务器已启动,等待客户端连接...");
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ClientHandler(socket)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 处理客户端请求的线程
private static class ClientHandler implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ClientHandler(Socket socket) throws Exception {
this.socket = socket;
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.writer = new PrintWriter(socket.getOutputStream(), true);
}
@Override
public void run() {
try {
while (true) {
String msg = reader.readLine();
if (msg != null) {
String[] parts = msg.split(",");
if (parts.length == 2) {
String action = parts[0];
String carId = parts[1];
if (action.equals("rent")) {
boolean success = rentalSystem.rentCar(carId);
if (success) {
writer.println("rent," + carId);
} else {
writer.println("rent_fail," + carId);
}
} else if (action.equals("return")) {
boolean success = rentalSystem.returnCar(carId);
if (success) {
writer.println("return," + carId);
} else {
writer.println("return_fail," + carId);
}
}
}
}
}
} catch (Exception e) {
System.out.println("客户端断开连接:" + e.getMessage());
} finally {
try {
reader.close();
writer.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
```
这个租车App的实现比较简单,仅供参考。实际上,一个完整的租车系统还需要考虑更多的功能,比如用户注册、登录、结算等等。