面向对象程序设计 课程实验 六

This commit is contained in:
JRNitre 2024-06-14 08:57:26 +08:00
parent 9f9cbdf1b8
commit 2ec5609876
30 changed files with 1001 additions and 28 deletions

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/untitled/ch11" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/untitled/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -1 +0,0 @@
7153-767-7764-9819-6754-3453-9423-86-5411-7717-9489-5214-5481-6695-8273

View File

@ -10,12 +10,12 @@ public class Customer implements Runnable{
// 用户姓名
private String customerName;
// 存取次数
private int customerNum;
private int customerNum = 3;
// 构造函数
public Customer (String customerName){
this.customerName = customerName;
}
// public Customer (String customerName){
// this.customerName = customerName;
// }
// 重写 run 方法
@Override
@ -23,7 +23,7 @@ public class Customer implements Runnable{
// 重复指定次数
for (int i = 0; i < this.customerNum; i++) {
// 输出用户存款信息
System.out.println("User: " + this.customerName + " Deposit 100");
System.out.println("User: " + Thread.currentThread().getName() + " Deposit 100");
// 调用存款方法
deposit(100);
}
@ -33,9 +33,4 @@ public class Customer implements Runnable{
private synchronized void deposit(int amount) {
Bank.Funds(amount);
}
// 设置存款次数
public void setDepositNum(int num){
this.customerNum = num;
}
}

View File

@ -39,22 +39,17 @@ public class test {
* Class
* 1. Bank.java
* 2. Customer.java
*
*/
// 通过 Bank 类实例化 b_1 对象
Bank b_1 = new Bank("Best Nigger Bank");
// 通过 Customer 实例化两个用户对象
Customer c_1 = new Customer("Todd");
Customer c_2 = new Customer("KoDick");
// 调用其中的方法设置每个人的存款次数
c_1.setDepositNum(3);
c_2.setDepositNum(3);
Customer c_1 = new Customer();
// 通过 Thread 实例化两个线程类
Thread t_1 = new Thread(c_1);
Thread t_2 = new Thread(c_2);
Thread t_1 = new Thread(c_1, "Todd");
Thread t_2 = new Thread(c_1, "Todd Copy");
// 在开始存款前输出一次银行当前的余额
System.out.println("Now Bank Balance: " + b_1.getBankBalance());
@ -74,6 +69,6 @@ public class test {
// 输出当前银行余额
System.out.println("Now Bank Balance: " + b_1.getBankBalance());
*/
/**/
}
}

View File

@ -0,0 +1,62 @@
/*
* Function: Java 课程实验 - 题目 01
* Date: 2024 06 14
* Code by: JRNitre
* */
package javaAssignment_20240614;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class function_01 extends Frame implements ActionListener{
Label userLabel, passLabel;
TextField userField;
JPasswordField passField;
Button loginButton;
public function_01() {
// 设置窗口属性
setTitle("User Login");
setSize(300, 200);
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// 添加组件
userLabel = new Label("User Id:");
add(userLabel);
userField = new TextField(15);
add(userField);
passLabel = new Label("Password:");
add(passLabel);
passField = new JPasswordField(15);
add(passField);
loginButton = new Button("Login");
loginButton.addActionListener(this);
add(loginButton);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loginButton) {
String username = userField.getText();
String password = new String(passField.getPassword());
if (isValidUser(username, password)) {
dispose(); // 关闭当前窗口
JOptionPane.showMessageDialog(null, "Login Done!");
} else {
JOptionPane.showMessageDialog(null, "Error!");
}
}
}
private boolean isValidUser(String username, String password) {
return "user".equals(username) && "pass".equals(password);
}
}

View File

@ -0,0 +1,96 @@
/*
* Function: Java 课程实验 - 题目 02
* Date: 2024 06 14
* Code by: JRNitre
* */
package javaAssignment_20240614;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class function_02 extends JFrame {
JLabel num1Label, num2Label, resultLabel;
JTextField num1Field, num2Field, resultField;
JComboBox<String> operationComboBox;
JButton calculateButton;
public function_02() {
super("计算器");
// 初始化组件
num1Label = new JLabel("数字1:");
num2Label = new JLabel("数字2:");
resultLabel = new JLabel("结果:");
num1Field = new JTextField(10);
num2Field = new JTextField(10);
resultField = new JTextField(10);
resultField.setEditable(false); // 结果字段不可编辑
operationComboBox = new JComboBox<>(new String[]{"+", "-", "*", "/"});
calculateButton = new JButton("计算");
// 添加动作监听器
calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calculate();
}
});
// 设置布局
setLayout(new GridLayout(4, 2));
// 添加组件到窗口
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(new JLabel()); // 空白占位
add(operationComboBox);
add(resultLabel);
add(resultField);
add(new JLabel()); // 空白占位
add(calculateButton);
// 设置窗口属性
setSize(300, 150);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null); // 居中显示
setVisible(true);
}
private void calculate() {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
String operation = (String) operationComboBox.getSelectedItem();
double result = 0;
switch (operation) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 != 0)
result = num1 / num2;
else {
JOptionPane.showMessageDialog(this, "除数不能为0!");
return;
}
break;
}
resultField.setText(String.valueOf(result));
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(this, "请输入有效的数字!");
}
}
}

View File

@ -0,0 +1,62 @@
/*
* Function: Java 课程实验 - 题目 03
* Date: 2024 06 14
* Code by: JRNitre
* */
package javaAssignment_20240614;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class function_03 {
public function_03(){
SwingUtilities.invokeLater(() -> {
createAndShowGUI();
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("选项事件处理");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
JTextArea textArea = new JTextArea("选顶事件ItemEvent的使用方法", 6, 20);
textArea.setEditable(false);
frame.add(textArea);
JRadioButton redButton = new JRadioButton("红色");
JRadioButton blueButton = new JRadioButton("蓝色");
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(blueButton);
ItemListener itemListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
Object source = e.getSource();
if (source == redButton) {
textArea.setForeground(Color.RED);
} else if (source == blueButton) {
textArea.setForeground(Color.BLUE);
}
}
}
};
redButton.addItemListener(itemListener);
blueButton.addItemListener(itemListener);
frame.add(redButton);
frame.add(blueButton);
frame.pack();
frame.setVisible(true);
}
}

View File

@ -0,0 +1,49 @@
/*
* Function: Java 课程实验
* Date: 2024 06 14
* Code by: JRNitre
* */
package javaAssignment_20240614;
public class test {
public static void main (String[] args){
/*
* 设计实现一个用户登录页面当单击登录按钮用户名密码正确跳转到计算页面
*
* Class: function_01.java
*
function_01 f_1 = new function_01();
*/
/* ( つ•̀ω•́)つ :-D */
/*
* 设计实现一个计算页面实现两个数的加法减法乘法和除法运算
*
* Class: function_02.java
*
function_02 f_2 = new function_02();
*/
/* ( つ•̀ω•́)つ :-D */
/*
* 编写一个应用程序标题为选项事件处理的窗口窗口布局为FlowLayout
* 设计两个单选按钮一个文本区
* 单击单选按钮时将文本区中的文字设置成为相应颜色的字体
*
* Class: function_03.java
*
function_03 f_3 = new function_03();
*/
}
}

View File

@ -1,10 +1,14 @@
package javaPackage_20240524;
import java.io.*;
import java.security.SecureRandom;
public class function {
// 数组长度
private int ArrayMaxLength;
private String fileName;
public int[] createRandomArray(int num, int min, int max){
this.ArrayMaxLength = num;
int[] array = new int[this.ArrayMaxLength];
@ -12,7 +16,76 @@ public class function {
for (int i = 0; i < this.ArrayMaxLength; i++){
array[i] = min + secureRandom.nextInt(max - min + 1);
}
System.out.println("Create Random Array Done!");
return array;
}
public void createFile (String fileName){
this.fileName = fileName;
File file = new File(fileName);
try {
if (file.createNewFile()){
System.out.println("Create file Done!");
} else {
System.out.println("Create file Error!");
}
} catch (IOException ioe){
System.out.println("Create file Error!");
ioe.printStackTrace();
}
}
public void writeFile (String data){
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(this.fileName));
writer.write(data);
writer.close();
System.out.println("Writer Done!");
} catch (IOException ioe){
System.out.println("Writer Error!");
}
}
public int[] readeFileToInt(){
try {
BufferedReader reader = new BufferedReader(new FileReader(this.fileName));
String line = reader.readLine();
String[] arrayStr = line.split("-");
int[] arrayInt = new int[this.ArrayMaxLength];
for (int i = 0; i < this.ArrayMaxLength; i++){
arrayInt[i] = Integer.parseInt(arrayStr[i]);
}
System.out.println("Reader File Done!");
return arrayInt;
} catch (IOException ioe){
System.out.println("Reader File Error!");
return new int[0];
}
}
public void bubbleSort(int[] array){
int m = array.length;
for (int i = 0; i < m; i++){
for (int j = 0; j < m - i - 1; i++){
if (array[j] > array[j+1]){
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
System.out.println("Sort Done!");
for (int k = 0; k < m; k++){
System.out.print(array[k]);
if (k != m - 1){
System.out.print(" - ");
}
}
}
}

View File

@ -9,6 +9,19 @@ public class test {
*/
function f_1 = new function();
f_1.createRandomArray(15, 20, 9999);
int array[] = f_1.createRandomArray(15, 20, 9999);
f_1.createFile("file2.txt");
StringBuilder s_1 = new StringBuilder();
for (int i = 0; i < array.length; i++){
s_1.append(array[i]);
if (i != array.length - 1){
s_1.append("-");
}
}
f_1.writeFile(s_1.toString());
f_1.bubbleSort(f_1.readeFileToInt());
}
}

View File

@ -0,0 +1,19 @@
package javaPackage_20240531;
public class bank {
private static int money;
private String bankNmae;
public bank (String name){
this.bankNmae = name;
}
public int getMoney(){
return money;
}
public static synchronized void add (int n){
money += n;
}
}

View File

@ -0,0 +1,19 @@
package javaPackage_20240531;
public class customer implements Runnable{
private static final int num = 3;
@Override
public void run(){
for (int i = 0; i < num; i++){
System.out.println("User: " + Thread.currentThread().getName() + " add 100");
customerAdd(100);
}
}
public synchronized void customerAdd(int n){
bank.add(n);
}
}

View File

@ -0,0 +1,28 @@
package javaPackage_20240531;
public class test {
public static void main (String[] args){
/*
* 1. 设某家银行可接受用户的存款每进行一次存款便可计算出存款的总额
* 2. 现有两名顾客每人分3次每次存入100元
*/
bank b = new bank("Bank");
customer c = new customer();
Thread t_1 = new Thread(c, "todd");
Thread t_2 = new Thread(c, "Copy todd");
System.out.println("Now Bank: " + b.getMoney());
t_1.start();
t_2.start();
try {
t_1.join();
t_2.join();
} catch (Exception e){}
System.out.println("Now Bank: " + b.getMoney());
}
}

View File

@ -0,0 +1,3 @@
# 默认忽略的文件
/shelf/
/workspace.xml

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/ElmAdminEntry.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/View/AdminView.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/View/display.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/dao/AdminDaoImpl.java" charset="GBK" />
<file url="file://$PROJECT_DIR$/src/jdbc/JDBC.java" charset="GBK" />
</component>
</project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/CourseExperiment.iml" filepath="$PROJECT_DIR$/CourseExperiment.iml" />
</modules>
</component>
</project>

View File

@ -0,0 +1,124 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="mysql-connector-j-8.4.0" level="project" />
</component>
</module>

View File

@ -0,0 +1,118 @@
import View.AdminView;
import View.Display;
import po.Admin;
import java.io.IOException;
import java.util.Scanner;
import java.util.stream.StreamSupport;
public class ElmAdminEntry {
public static void main(String[] args){
new ElmAdminEntry().work();
}
public void work(){
Integer mistake = 0;
Integer maxMistake = 3;
Integer errorCode = 0;
Integer mainExitCode = 0;
Scanner sca = new Scanner(System.in);
AdminView adminView = new AdminView();
Display dis = new Display('+', '-', 30);
while (mistake < maxMistake && mainExitCode == 0){
dis.titleLine("登录 饿了么后台管理系统", true);
if (mistake != 0){
System.out.println("+ 当前错误次数: " + mistake + " 剩余次数: " + (maxMistake - mistake));
}
System.out.print("+ 账户: ");
String userInputAdminName = sca.next();
System.out.print("+ 密码: ");
String userInputAdminPassworld = sca.next();
Admin admin = adminView.login(userInputAdminName, userInputAdminPassworld);
if (admin != null){
int key = -1;
while (key != 10){
dis.titleLine("Admin - " + admin.getAdminName(), true);
dis.showItem("[0] 所有商家列表", true);
dis.showItem("[1] 搜索商家", true);
dis.showItem("[2] 新建商家", true);
dis.showItem("[3] 删除商家", true);
dis.showItem("[4] 查看管理员信息", true);
dis.showItem("[5] 设置管理员密码", true);
dis.showItem("[10] 退出系统", true);
dis.showLine(true);
System.out.print("+ 请输入对应的操作数: ");
key = sca.nextInt();
switch (key){
case 0:
break;
case 1:
case 2:
case 3:
case 4:
// TODO 解决 nextLine 问题
dis.titleLine("管理员信息", true);
System.out.println("+ 管理员 ID:\t" + admin.getAdminId());
System.out.println("+ 管理员名:\t" + admin.getAdminName());
System.out.println("+ 管理员密码:\t" + admin.getAdminPassword());
sca.nextLine();
break;
case 5:
dis.titleLine("设置管理员密码", true);
System.out.print("+ 输入当前密码: ");
String newPassword = sca.next();
if (!(newPassword.equals(admin.getAdminPassword()))){
dis.titleLine("ERROR", true);
System.out.println("密码不一致!");
break;
}
// TODO 密码校验
System.out.println("+ 输入新密码: ");
newPassword = sca.next();
admin.setAdminPassword(newPassword);
adminView.updatePassword(admin);
break;
case 10:
errorCode = 2;
mainExitCode = 1;
break;
default:
dis.titleLine("ERROR", true);
System.out.println("+ 操作数不合法!");
break;
}
}
} else {
mistake++;
}
if (mistake >= maxMistake){
errorCode = 1;
}
}
if (errorCode == 1){
dis.titleLine("ERROR", true);
System.out.println("+ 错误次数过多,退出系统!");
System.exit(0);
}
if (errorCode == 2){
dis.titleLine("提示", true);
System.out.println("+ 系统退出");
System.exit(0);
}
}
}

View File

@ -0,0 +1,22 @@
package View;
import dao.AdminDaoImpl;
import po.Admin;
import java.util.Scanner;
public class AdminView {
public Admin login(String name, String passworld){
Admin admin = null;
admin = new AdminDaoImpl().getAdminByNameByPass(name, passworld);
return admin;
}
public void updatePassword(Admin admin){
System.out.println("+ ÃÜÂë¸üÐÂÖÐ...");
new AdminDaoImpl().updateAdminPassword(admin);
}
}

View File

@ -0,0 +1,70 @@
package View;
public class Display {
private char displayNode;
private char displayLine;
private Integer displayWidth;
public Display (char node, char line, Integer width){
displayNode = node;
displayLine = line;
displayWidth = width;
}
public void setWidth(Integer width){
displayWidth = width;
}
public void titleLine (String title, boolean newLine){
StringBuilder str = new StringBuilder();
Integer space = (displayWidth - title.length() - 2) / 2;
str.append(displayNode);
for (int i = 0; i < space; i++){
str.append(displayLine);
}
str.append(title);
for (int i = 0; i < space; i++){
str.append(displayLine);
}
str.append(displayNode);
System.out.print(str.toString());
if (newLine){
System.out.println();
}
}
public void showItem(String item, boolean newLine){
StringBuilder str = new StringBuilder();
str.append(displayNode).append(" ");
str.append(item);
Integer space = displayWidth - 1 - ("+ ".length() + item.length());
System.out.print(str.toString());
if (newLine){
System.out.println();
}
}
public void showLine(boolean newLine){
StringBuilder str = new StringBuilder();
str.append(displayNode);
for (int i = 0; i < displayWidth - 2; i++){
str.append(displayLine);
}
str.append(displayNode);
System.out.print(str.toString());
if (newLine){
System.out.println();
}
}
}

View File

@ -0,0 +1,9 @@
package dao;
import po.Admin;
public interface AdminDao {
Admin getAdminByNameByPass(String adminName, String password);
void updateAdminPassword(Admin admin);
}

View File

@ -0,0 +1,76 @@
package dao;
import jdbc.JDBC;
import po.Admin;
import java.sql.*;
public class AdminDaoImpl implements AdminDao{
// @Override
// public Admin getAdminByNameByPass(String adminName, String password){
// Map<Integer, Admin> map = AdminMap.ADMIN_MAP;//取得所有管理员的数据
// Collection<Admin> values = map.values();//取得map中值的集合
//
// //遍历值的集合判断是否有数据与参数的名称和密码匹配如果有则表示登录成功
// Admin admin = null;
// for(Admin tmp : values ) {
// if(tmp.getAdminName().equals(adminName) && tmp.getAdminPassworld().equals(password)) {
// admin = tmp;
// break;
// }
// }
//
// return admin;
// }
@Override
public Admin getAdminByNameByPass(String adminName, String password) {
Admin admin = null;
try {
// 连接数据库
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
String sql = "SELECT * FROM admin WHERE adminName = '" + adminName + "' AND adminPassword = '" + password + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
admin = new Admin();
admin.setAdminId(rs.getInt("adminId"));
admin.setAdminName(rs.getString("adminName"));
admin.setAdminPassword(rs.getString("adminPassword"));
}
conn.close();
stmt.close();
rs.close();
} catch (SQLException e) {
System.err.println("Database error occurred: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
return admin;
}
@Override
public void updateAdminPassword(Admin admin) {
// TODO 完善密码更新功能
try {
Connection conn = JDBC.getConnection();
Statement stmt = conn.createStatement();
System.out.println("+ 连接到数据库");
String sql = "UPDATE admin SET adminPassword = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, admin.getAdminPassword());
pst.executeUpdate();
System.out.println("+ 更新完毕");
stmt.close();
conn.close();
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
}
}

View File

@ -0,0 +1,15 @@
package data;
import java.util.HashMap;
import java.util.Map;
import po.Admin;
public class AdminMap {
public static final Map<Integer, Admin> ADMIN_MAP = new HashMap<>();
static {
ADMIN_MAP.put(1, new Admin(1, "jrnitre", "123"));
}
}

View File

@ -0,0 +1,23 @@
package jdbc;
import po.Admin;
import java.beans.Expression;
import java.sql.*;
public class JDBC {
private static final String URL = "jdbc:mysql://124.220.110.170:3306/jrnitre";
private static final String user = "jrnitre";
private static final String Password = "npgt1365";
public static Connection getConnection() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(URL, user, Password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
throw new RuntimeException("Êý¾Ý¿âÁ¬½Óʧ°Ü", e);
}
}
}

View File

@ -0,0 +1,45 @@
package po;
public class Admin {
// 管理员 ID
private Integer adminId;
// 管理员名
private String adminName;
// 管理员密码
private String adminPassword;
public Admin (Integer id, String name, String passworld){
super();
adminId = id;
adminName = name;
adminPassword = passworld;
}
public Admin (){
super();
}
public Integer getAdminId(){
return adminId;
}
public String getAdminName(){
return adminName;
}
public String getAdminPassword(){
return adminPassword;
}
public void setAdminId(Integer id){
adminId = id;
}
public void setAdminName(String name){
adminName = name;
}
public void setAdminPassword(String password){
adminPassword = password;
}
}

View File

@ -0,0 +1,4 @@
package po;
public class Business {
}