目录
1.1 前言
- ATM 1.0 是一个 Java 控制台程序,简单模拟了银行基础自助业务,即用户简单验证,查询余额,取款,存款,修改密码等。
- 难度级别:入门。
1.2 工具准备
- Java 编译器:IDEA;
- 数据库:MySQL;
1.3 知识储备
MySQL:创建数据库语句,创建数据表语句,查询语句,更新语句;
Java:
1. 包;
2. 对象类:命名约定,类,构造函数,static 关键字;
3. 继承;
4. 访问修饰符;
5. 基础正则表达式;
6. 异常处理:try - catch 块,throws 关键字;
7. JDBC:基本流程,IDEA 加载 MySQL 驱动;
8. I/O 输入和输出:标准输入流(System.in),标准输出流(System.out),标准错误流(System.err);
9. 流程控制:条件语句,for 循环,switch;
1.4 界面演示
输入卡号和密码
卡号或者密码输入错误
功能界面
查询余额
取款
存款
修改密码
退出
1.5 数据库
- 数据库名:bankingSystem;
- 数据表名:atm;
- 表列名及属性:卡号:cardID —— varchar(16),密码:password —— varchar(20),余额:money —— decimal(9,2)。除了 money 其余列名均不允许为空;
- 语句:
// 创建数据库 create database bankingSystem; // 创建数据表,注意不是单引号,不是单引号,是 Tab 键上面的键 create table if not exists `atm`( `cardID` varchar(16) not null, `password` varchar(20) not null, `money` decimal(9,2) )engine=InnoDB default charset=utf8; // 查询语句 select * from `bankingSystem`.`atm` where cardID = 'cardNumber' // 查询数量 select count(*) from `bankingSystem`.`atm` where cardID = 'cardNumber' and password = ' password' // 更改语句 update `bankingSystem`.`atm` set money = 'balance' where cardID = 'cardID'
1.7 源码展示
建议:学完知识后,按照流程图自己敲,不会的时候才看看我的代码;
package page;
import java.awt.*;
import java.sql.SQLException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import tool.ClearConsole;
import tool.ConnectionSQL;
import tool.PrintWelcome;
/**
* ATM 系统主界面
* @author:Picachu
* @version:1.0
*/
public class MainPage {
// 卡号
public static String cardNumber;
// 密码
public static String password;
static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) throws ClassNotFoundException, SQLException, AWTException {
MainPage mainPage = new MainPage();
mainPage.runMain();
}
/*
主运行
*/
public void runMain() throws SQLException {
boolean isCustomer;
int chooseInt;
isCustomer = userAuthentication();
if (isCustomer == true) {
MainPage mainPage = new MainPage();
mainPage.printFunction();
mainPage.choicePage();
}
else {
System.out.println("您输入卡号或用户名有误,可按 1 重新输入或按 2 退出系统");
chooseInt = scanner.nextInt();
MainPage mainPage = new MainPage();
switch (chooseInt) {
case 1:
mainPage.runMain();
break;
case 2:
System.exit(1);
break;
default:
break;
}
}
}
/*
用户验证
*/
public boolean userAuthentication() throws SQLException {
boolean isCustomer = false;
// 清屏
ClearConsole clearConsole = new ClearConsole();
// 打印欢迎界面
PrintWelcome printWelcome = new PrintWelcome();
// 用户验证开始
System.out.print("请输入卡号:");
cardNumber = scanner.next();
System.out.print("请输入密码:");
password = scanner.next();
// 连接数据库
String countSql = "select count(*) from `bankingSystem`.`atm` where cardID = " + cardNumber + " and password = " + password;
ConnectionSQL connectionSQL = new ConnectionSQL();
isCustomer = connectionSQL.selectCount(countSql);
// 返回验证结果
return isCustomer;
}
/*
* 打印功能页面
*/
public void printFunction() {
// 清屏
ClearConsole clearConsole = new ClearConsole();
// 打印欢迎界面
PrintWelcome printWelcome = new PrintWelcome();
// 打印功能页面
for (int i = 0; i < 26; i++) {
System.out.print("*");
}
System.out.print("\n");
System.out.println("请选择下列功能对应的数字");
System.out.println("\t1.查询余额");
System.out.println("\t2.取款");
System.out.println("\t3.存款");
System.out.println("\t4.修改密码");
System.out.println("\t5.退出");
for (int i = 0; i < 26; i++) {
System.out.print("*");
}
System.out.print("\n");
System.out.println("请输入数字对应选项:");
}
/*
选择功能
*/
public void choicePage() throws SQLException {
// 输入选择的功能键
String chooseFunction = scanner.next();
boolean isFunctionNum;
MainPage mainPage = new MainPage();
// 正则表达式,对照输入的功能键是否在 1-5 范围内
Pattern pattern = Pattern.compile("[1-5]");
Matcher matcher = pattern.matcher(chooseFunction);
isFunctionNum = matcher.matches();
if (isFunctionNum == false) {
System.out.println("您输入的数字不是功能键,请重新输入:");
mainPage.choicePage();
}
else {
switch (chooseFunction) {
case "1":
mainPage.selectAllMoney();
break;
case "2":
mainPage.withdrawal();
break;
case "3":
mainPage.deposit();
break;
case "4":
mainPage.verifyPassword();
break;
case "5":
System.exit(1);
break;
default:
break;
}
}
}
/*
1.查询余额
*/
public void selectAllMoney() throws SQLException {
double money = 0;
// 连接数据库
String selectMoneySql = "select * from `bankingSystem`.`atm` where cardID =" + cardNumber;
ConnectionSQL connectionSQL = new ConnectionSQL();
money = connectionSQL.selectMoney(selectMoneySql);
System.out.print("您当前的账户余额是:¥" + money + "\n");
// 询问用户是否继续
MainPage mainPage = new MainPage();
mainPage.exitOrContinue();
}
/*
2. 取款
*/
public void withdrawal() throws SQLException {
double inputMoney = 0, balance = 0, allMoney = 0;
boolean isSuccess = false;
// 连接数据库
ConnectionSQL connectionSQL = new ConnectionSQL();
allMoney = connectionSQL.selectMoney("select * from `bankingSystem`.`atm` where cardID = " + cardNumber);
System.out.print("请输入取款金额:-¥");
// 输入金额
inputMoney = scanner.nextDouble();
// 计算余额
balance = allMoney - inputMoney;
// 连接数据库
connectionSQL.updateMoney(balance,cardNumber);
// 修改成功
isSuccess = true;
if (isSuccess == true) {
allMoney = connectionSQL.selectMoney("select * from `bankingSystem`.`atm` where cardID = " + cardNumber);
System.out.println("交易成功,当前账户余额:¥" + allMoney);
}
else {
System.out.println("系统异常,交易失败");
}
// 询问用户是否继续
MainPage mainPage = new MainPage();
mainPage.exitOrContinue();
}
/*
3. 存款
*/
public void deposit() throws SQLException {
double inputMoney = 0, balance = 0, allMoney = 0;
boolean isSuccess = false;
// 连接数据库
ConnectionSQL connectionSQL = new ConnectionSQL();
allMoney = connectionSQL.selectMoney("select * from `bankingSystem`.`atm` where cardID = " + cardNumber);
System.out.print("请输入存款金额:+¥");
// 输入金额
inputMoney = scanner.nextDouble();
// 计算余额
balance = allMoney + inputMoney;
// 更新余额
connectionSQL.updateMoney(balance,cardNumber);
isSuccess = true;
if (isSuccess == true) {
allMoney = connectionSQL.selectMoney("select * from `bankingSystem`.`atm` where cardID = " + cardNumber);
System.out.println("交易成功,当前账户余额:¥" + allMoney);
}
else {
System.out.println("系统异常,交易失败");
}
// 询问用户是否继续
MainPage mainPage = new MainPage();
mainPage.exitOrContinue();
}
// 输入密码的次数,与输入密码前身份验证相关
static int inputCount = 0;
/*
4. 输入密码前身份验证
*/
public void verifyPassword() throws SQLException {
String oldPassword = "0";
boolean isOldPassword = false;
// 输入原密码验证身份
System.out.println("身份验证");
System.out.println("请输入原密码");
oldPassword = scanner.next();
// 正则表达式,对照新旧密码是否相同
Pattern pattern = Pattern.compile(password);
Matcher matcher = pattern.matcher(oldPassword);
isOldPassword = matcher.matches();
MainPage mainPage = new MainPage();
inputCount++;
if (isOldPassword == false && inputCount < 3) {
System.out.println("密码不一致,请重新输入,输入三次将会重新进行用户验证");
verifyPassword();
}
else if (isOldPassword == false && inputCount >= 3) {
mainPage.runMain();
}
else {
inputCount = 0;
mainPage.updateMyPassword();
}
}
/*
4. 修改密码
*/
public void updateMyPassword() throws SQLException {
String firstPassword, newPassword;
boolean isPWDSame = false, isSuccess = false;
int inputNum;
// 输入新密码并确认密码
System.out.println("开始修改密码");
System.out.println("请输入新密码:");
firstPassword = scanner.next();
System.out.println("请确认新密码:");
newPassword = scanner.next();
// 正则表达式,对照两次输入的密码
Pattern pattern = Pattern.compile(firstPassword);
Matcher matcher = pattern.matcher(newPassword);
isPWDSame = matcher.matches();
MainPage mainPage = new MainPage();
if (isPWDSame == false) {
System.out.println("您输入的密码不一致,请按 1 重新输入或按 0 返回");
inputNum = scanner.nextInt();
switch (inputNum) {
case 0:
mainPage.printFunction();
mainPage.choicePage();
break;
case 1:
mainPage.updateMyPassword();
break;
default:
break;
}
}
else {
// 连接数据库
ConnectionSQL connectionSQL = new ConnectionSQL();
isSuccess = connectionSQL.updatePassword(newPassword, cardNumber);
}
if (isSuccess == true) {
System.out.println("修改成功");
}
else {
System.out.println("系统异常,更新失败");
}
// 询问用户是否继续
mainPage.exitOrContinue();
}
/*
继续或退出
*/
public void exitOrContinue() {
System.out.println("按 1 继续,按其他健则退出");
int inputNum = scanner.nextInt();
MainPage mainPage = new MainPage();
switch (inputNum) {
case 1:
mainPage.printFunction();
try {
mainPage.choicePage();
}
catch (SQLException e) {
System.err.println("JDBC 出问题");
}
break;
default:
break;
}
}
}
package tool;
import java.sql.*;
import java.text.DecimalFormat;
/**
* 数据库类
* @author:Picachu
* @version:1.0
*/
public class ConnectionSQL {
public static Connection connection;
public static Statement statement;
public static ResultSet resultSet;
public static PreparedStatement preparedStatement;
/*
* 加载驱动程序,连接数据库
*/
public void connectionMySql() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankingSystem?characterEncoding=utf8","root","201914");
}
/*
* 用户验证
*/
public boolean selectCount(String selectCountStr) throws SQLException {
int count = 0;
try {
connectionMySql();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(selectCountStr);
try {
if (resultSet.next()) {
count = resultSet.getInt(1);
}
}
catch (SQLException e) {
System.err.println("无法获取数据行数");
}
}
catch (SQLException e) {
System.err.println("查询语句执行失败");
}
}
catch (ClassNotFoundException e) {
System.err.println("驱动程序加载失败");
}
catch (SQLException e) {
System.out.println("数据库连接失败");
}
finally {
resultSet.close();
statement.close();
connection.close();
}
if (count == 1) {
return true;
}
else {
return false;
}
}
/*
查询余额
*/
public double selectMoney(String selectMoneyStr) throws SQLException {
double money = 0;
try {
connectionMySql();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(selectMoneyStr);
try {
if(resultSet.next()) {
money = resultSet.getDouble("money");
}
}
catch (SQLException e) {
System.err.println("获取余额失败");
}
}
catch (SQLException e) {
System.err.println("查询语句执行失败");
}
}
catch (ClassNotFoundException e) {
System.err.println("驱动程序加载失败");
}
catch (SQLException e) {
System.out.println("数据库连接失败");
}
finally {
resultSet.close();
statement.close();
connection.close();
}
return money;
}
/*
更新余额
*/
public void updateMoney(double balance, String cardID) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankingSystem?characterEncoding=utf8","root","201914");
try {
String updateMoneySql = "update `bankingSystem`.`atm` set money = " + balance + " where cardID = " + cardID;
preparedStatement = connection.prepareStatement(updateMoneySql);
try {
preparedStatement.executeUpdate();
}
catch (SQLException e) {
System.err.println("更新语句执行失败");
}
finally {
preparedStatement.close();
}
}
catch (SQLException e) {
System.err.println("预置对象失败");
}
}
catch (ClassNotFoundException e) {
System.err.println("未能连接数据库");
}
catch (SQLException e) {
System.out.println("数据库连接失败");
}
finally {
connection.close();
}
}
/*
* 更新密码
*/
public boolean updatePassword(String newPassword, String cardID) throws SQLException {
boolean isSuccess = false;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/bankingSystem?characterEncoding=utf8","root","201914");
try {
String updateMoneySql = "update `bankingSystem`.`atm` set password = " + newPassword + " where cardID = " + cardID;
preparedStatement = connection.prepareStatement(updateMoneySql);
try {
preparedStatement.executeUpdate();
isSuccess = true;
}
catch (SQLException e) {
System.err.println("更新语句执行失败");
}
finally {
preparedStatement.close();
}
}
catch (SQLException e) {
System.err.println("预置对象失败");
}
}
catch (ClassNotFoundException e) {
System.err.println("未能连接数据库");
}
catch (SQLException e) {
System.out.println("数据库连接失败");
}
finally {
connection.close();
}
return isSuccess;
}
}
package tool;
import java.awt.*;
import java.awt.event.KeyEvent;
/**
* ATM 系统控制台清屏工具
* @author:Picachu
* @version:1.0
*/
public class ClearConsole {
public ClearConsole() {
try {
// 实例化一个 Robot 类
Robot robot = new Robot();
// 按下 ctrl 键
robot.keyPress(KeyEvent.VK_CONTROL);
// 按下 alt 键
robot.keyPress(KeyEvent.VK_ALT);
// 按下 backspace 键
robot.keyPress(KeyEvent.VK_BACK_SPACE);
// 松开 backspace 键
robot.keyRelease(KeyEvent.VK_BACK_SPACE);
// 松开 alt 键
robot.keyRelease(KeyEvent.VK_ALT);
// 松开 ctrl 键
robot.keyRelease(KeyEvent.VK_CONTROL);
// 时延 100 毫秒
robot.delay(100);
}
catch (AWTException e) {
System.out.println(e.toString());
}
}
}
package tool;
/**
* ATM 系统欢迎界面
* @author:Picachu
* @version:1.0
*/
public class PrintWelcome {
public PrintWelcome() {
for (int i = 0; i < 26; i++) {
System.out.print("*");
}
System.out.print("\n");
System.out.print("**" + "\t欢迎使用 ATM 1.0\t" + "**");
System.out.print("\n");
for (int i = 0; i < 26; i++) {
System.out.print("*");
}
System.out.print("\n");
}
}