用Java写一个电影购票系统的代码,要求使用文件操作,有顾客和商家两种身份登陆与操作
时间: 2024-03-18 18:41:33 浏览: 16
好的,以下是一个简单的电影购票系统的Java代码,其中使用了文件操作,实现了顾客和商家两种不同身份的登陆和操作:
```
import java.util.Scanner;
import java.io.*;
public class MovieTicketSystem {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("欢迎使用电影购票系统!");
while (true) {
System.out.println("请选择您的身份:");
System.out.println("1.顾客\t2.商家\t3.退出");
int identity = input.nextInt();
if (identity == 1) {
// 顾客身份
System.out.println("请输入您的用户名:");
String username = input.next();
System.out.println("请输入您的密码:");
String password = input.next();
if (checkCustomerLogin(username, password)) {
// 登陆成功
System.out.println("登陆成功!");
System.out.println("请选择您要购买的电影:");
// TODO: 显示电影列表并让用户选择购买
} else {
// 登陆失败
System.out.println("用户名或密码错误,请重新输入!");
}
} else if (identity == 2) {
// 商家身份
System.out.println("请输入您的用户名:");
String username = input.next();
System.out.println("请输入您的密码:");
String password = input.next();
if (checkMerchantLogin(username, password)) {
// 登陆成功
System.out.println("登陆成功!");
System.out.println("请选择您要进行的操作:");
// TODO: 显示商家操作菜单并让用户选择操作
} else {
// 登陆失败
System.out.println("用户名或密码错误,请重新输入!");
}
} else if (identity == 3) {
// 退出程序
System.out.println("谢谢使用电影购票系统!");
break;
} else {
// 输入错误
System.out.println("输入有误,请重新输入!");
}
}
input.close();
}
// 检查顾客登陆信息是否正确
public static boolean checkCustomerLogin(String username, String password) {
try {
File file = new File("customer.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
String[] line = input.nextLine().split(",");
if (line[0].equals(username) && line[1].equals(password)) {
input.close();
return true;
}
}
input.close();
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
// 检查商家登陆信息是否正确
public static boolean checkMerchantLogin(String username, String password) {
try {
File file = new File("merchant.txt");
Scanner input = new Scanner(file);
while (input.hasNext()) {
String[] line = input.nextLine().split(",");
if (line[0].equals(username) && line[1].equals(password)) {
input.close();
return true;
}
}
input.close();
return false;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
}
```
上面的代码实现了一个简单的电影购票系统,包括顾客和商家两种不同的身份登陆和操作。其中,`checkCustomerLogin` 和 `checkMerchantLogin` 方法通过读取文件来检查用户的登陆信息是否正确,文件名分别为 `customer.txt` 和 `merchant.txt`,文件格式为每行一个用户信息,用逗号分隔用户名和密码。在实际应用中,还需要实现电影列表的显示和购票、商家操作的实现等功能。