英語背單詞專案(資料庫中是4級單詞)

moon_leaves發表於2020-12-06

寫這個部落格是想希望能夠幫到碼農們背單詞,在Main直接可以執行,修改startTest的方法能夠測試英文和中文,修改數字flag能夠修改背單詞的範圍,能寫1—9。在這裡插入圖片描述在這裡插入圖片描述

Main

package com.Main;

import com.utils.MybatisUtils;
import com.utils.StartTest;
import org.apache.ibatis.session.SqlSession;

import java.util.Scanner;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-28 10:30
 */
public class Main {
    public static void main(String[] args) {
//        先獲取sqlSession
        SqlSession sqlSession = MybatisUtils.getSqlSession();
//        建立scanner
        Scanner scanner = new Scanner(System.in);
//        通過密碼後呼叫執行的方法
        StartTest startTest = new StartTest();
//        在startTest裡有兩個方法,有兩個操作,這裡是一個
//        startTest.StartTestChinese(1, sqlSession, scanner);
        startTest.StartTestChinese(1, sqlSession, scanner);
        System.out.println();
        System.out.println("你真棒呢,本輪問題回答完畢了哦!");
        scanner.close();
    }
}


UserMapper

package com.Mapper;

import com.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.sql.SQLException;
import java.util.List;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-27 19:50
 */
public interface UserMapper {
    //    自動新增的score
    @Insert("insert into user (name,password,id,score) values (#{name},'123456',#{id},0);")
    int addUserAutoScore(User user) throws SQLException;

    //    設定score
    @Insert("insert into user (name,password,id,score) values(#{name},#{password},#{id},#{score})")
    int addUserSetScoreAndPassword(User user) throws SQLException;

    //      刪除使用者
    @Delete("delete from user where id = #{id}")
    int deleteUserById(@Param("id") int id);

    //根據id查詢使用者
    @Select("select * from user where id=#{id}")
    User selectUserById(@Param("id") int id);

    /**
     * 這個是寫在sql裡的
     * 返回所有的使用者
     * @return User的List集合
     */
    List<User> getAllUser();

}

UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Mapper.UserMapper">

    <select id="getAllUser" resultType="com.pojo.User">
        select * from user ;
    </select>
</mapper>

WordsMapper

package com.Mapper;

import com.pojo.Words;

import java.util.List;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-27 19:05
 */
public interface WordsMapper {
    /**
     * 獲取所有物件
     * @return Words的List集合
     */
    List<Words> getAllWords();

    /**
     * 獲取一個物件
     * @param id
     * @return com.pojo.Words
     */
    Words getWordById(int id);

    /**
     * 這個是實際呼叫
     * flag是傳入的單詞區間
     * 返回一個words集合物件,也就是一個資料來源
     * @param flag
     * @return Words的List集合
     */
    List<Words> getWords(int flag);

    /**
     * 獲取總的單詞數目個數long
     * @return long
     */
    long getTotalNumberOfWords();
}

WordsMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Mapper.WordsMapper">

    <!--    獲取一個物件-->
    <select id="getWordById" resultType="com.pojo.Words" parameterType="int">
    select * from words where id=#{id};
</select>

    <!--    獲取所有物件-->
    <select id="getAllWords" resultType="com.pojo.Words">
        select * from words ;
    </select>

    <!--    實際呼叫-->
    <select id="getWords" resultType="com.pojo.Words" parameterType="int">
        select * from words where 1=1
        <if test="#{flag}!=null and flag==1">
            and id &lt;= 500 &amp;&amp; id &gt;=1
        </if>
        <if test="#{flag}!=null and flag==2">
            and id &lt;= 1000 &amp;&amp; id &gt;=501
        </if>
        <if test="#{flag}!=null and flag==3">
            and id &lt;=1500 &amp;&amp; id &gt;=1001
        </if>
        <if test="#{flag}!=null and flag==4">
            and id &lt;= 2000 &amp;&amp; id &gt;=1501
        </if>
        <if test="#{flag}!=null and flag==5">
            and id &lt;= 2500 &amp;&amp; id &gt;=2001
        </if>
        <if test="#{flag}!=null and flag==6">
            and id &lt;=3000 &amp;&amp; id &gt;=2501
        </if>
        <if test="#{flag}!=null and flag==7">
            and id &lt;= 3500 &amp;&amp; id &gt;=3001
        </if>
        <if test="#{flag}!=null and flag==8">
            and id &lt;= 4000 &amp;&amp; id &gt;=3501
        </if>
        <if test="#{flag}!=null and flag==9">
            and id &lt;=4500 &amp;&amp; id &gt;=4001
        </if>
    </select>
    <!--    返回總單詞數目-->
    <select id="getTotalNumberOfWords" resultType="long">
    select count(*) from words;
    </select>
</mapper>

User

package com.pojo;

import java.util.Objects;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-27 15:27
 */
public class User {
    private String name;
    private int score;
    private int id;
    private String password;

    public User(String name, String password, int id, int score ){
        this.name = name;
        this.score = score;
        this.id = id;
        this.password = password;
    }

    public User(String name, String password , int id) {
        this.name = name;
        this.id = id;
        this.password = password;
    }

    @Override
    public String toString() {
        return "com.pojo.User{" +
                "name='" + name + '\'' +
                ", score=" + score +
                ", id=" + id +
                ", password='" + password + '\'' +
                '}';
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public User() {
    }

    public String getName() {
        return name;
    }

    public User(String name, int id) {
        this.name = name;
        this.id = id;
//        建立一個使用者時,基礎分數都為0
        this.score=0;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return score == user.score &&
                id == user.id &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return 0;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }


}

Words

package com.pojo;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-27 15:37
 */
public class Words {
    private String Word;
    private String ChineseMeaning;
    private int id;
    private int group;

    public Words(String word, String chineseMeaning, int id, int group) {
        Word = word;
        ChineseMeaning = chineseMeaning;
        this.id = id;
        this.group = group;
    }

    public Words(String word, String chineseMeaning, int id) {
        Word = word;
        ChineseMeaning = chineseMeaning;
        this.id = id;
        this.group=0;
    }

    public String getWord() {
        return Word;
    }

    public void setWord(String word) {
        Word = word;
    }

    public String getChineseMeaning() {
        return ChineseMeaning;
    }

    public void setChineseMeaning(String chineseMeaning) {
        ChineseMeaning = chineseMeaning;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getGroup() {
        return group;
    }

    public void setGroup(int group) {
        this.group = group;
    }

    @Override
    public String toString() {
        return "com.pojo.Words{" +
                "Word='" + Word + '\'' +
                ", ChineseMeaning='" + ChineseMeaning + '\'' +
                ", id=" + id +
                ", group=" + group +
                '}';
    }

    public Words() {
    }
}

JundgeWords

package com.utils;

import com.Mapper.WordsMapper;
import com.pojo.Words;
import org.apache.ibatis.session.SqlSession;

import java.util.*;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-27 19:56
 */
public class JudgeWords {
    public static int num=0;
    /**
     * 這個函式被testChineseMeaning所呼叫,目的是判斷你做的答案是否正確
     * <p>
     * 在裡面建立兩個陣列,ChineseArray和TrueChineseArray,分別儲存測試者回答的每個詞語和答案的每個詞語
     * 建立一個SetList集合,裡面事先儲存ChineseArray的每個值,然後利用add方法判斷TrueChineseArray的每個值是否可以加入
     * 如果能新增,就是不相同,即回答錯誤
     *
     * @param chineseMeaning
     * @param word
     * @return
     */
    public static boolean JudgeChineseMeaning(String chineseMeaning, Words word) {

        boolean result = false;
        String regex = "\\s";

        //自己的回答
        Set<String> SetList = new HashSet<>();
        //每一項,自己回答的長度
        String[] ChineseArray = chineseMeaning.split(regex);
        for (int i = 0; i < ChineseArray.length; i++) {
            String s = ChineseArray[i];
            SetList.add(s);
        }
        String TrueChinese = word.getChineseMeaning();
        //正確答案的陣列
        String[] TrueChineseArray = TrueChinese.split(regex);
        for (int i = 0; i < TrueChineseArray.length; i++) {
            if (!SetList.add(TrueChineseArray[i])) {
                result = true;
                break;
            }
        }
        return result;
    }

    /**
     * 這個函式被testEnglish所呼叫,目的是判斷你做的答案是否正確
     *
     * @param English
     * @param word
     * @return
     */
    public static boolean JudgeEnglish(String English, Words word) {
        return English.equals(word.getWord());
    }

    /**
     * 這個函式是核心程式,傳入資料集,然後進行流程
     *
     * @param wordsList
     * @param sqlSession
     */
    public static void testEnglish(List<Words> wordsList, SqlSession sqlSession, Scanner scanner) {
        for (Words word : wordsList) {
            System.out.println("目前得分是"+num);
            System.out.print("請看題目: ");
            String chineseMeaning = word.getChineseMeaning();
            System.out.println(chineseMeaning);
            System.out.println("請輸入單詞的英文:");
            String EnglishAnswer = scanner.next();
            boolean b = JudgeWords.JudgeEnglish(EnglishAnswer, word);
            if (b) {
                System.out.println("回答正確,你真棒呢\n");
                num++;
            } else {
                System.out.println("回答錯誤哦,請再次嘗試");
                EnglishAnswer = scanner.next();
                if (JudgeWords.JudgeEnglish(EnglishAnswer, word)) {
                    System.out.println("回答正確,你真棒呢\n");
                    num++;
                } else
                    System.out.println("在鞏固一下吧,正確答案是:" + word.getWord());
                System.out.println();
            }
        }

    }

    /**
     * 這個函式是核心程式,傳入資料集,然後進行流程
     *
     * @param wordsList
     * @param sqlSession
     */
    public static void testChineseMeaning(List<Words> wordsList, SqlSession sqlSession, Scanner scanner) {
        for (Words word : wordsList) {
            System.out.print("請看題目: ");
            String EnglishWord = word.getWord();
            System.out.println(EnglishWord);
            System.out.println("請輸入單詞的漢語:");
            String ChineseAnswer = scanner.nextLine();
            boolean b = JudgeWords.JudgeChineseMeaning(ChineseAnswer, word);
            if (b) {
                System.out.println("回答正確,你真棒呢\n");
                num++;
                System.out.println("目前得分是"+num);
            } else {
                System.out.println("回答錯誤哦,請再次嘗試");
                String TwoChineseAnswer = scanner.nextLine();
                if (JudgeWords.JudgeChineseMeaning(TwoChineseAnswer, word)) {

                    System.out.println("回答正確,你真棒呢\n");
                    num++;
                    System.out.println("目前得分是"+num);
                } else
                    System.out.println("在鞏固一下吧,正確答案是:" + word.getChineseMeaning());
                System.out.println();

            }
        }
    }

    /**
     * 返回資料集
     *
     * @param flag
     * @param sqlSession
     */
    public static List<Words> ChooseRange(int flag, SqlSession sqlSession) {
        WordsMapper mapper = sqlSession.getMapper(WordsMapper.class);
        List<Words> wordsList = mapper.getWords(flag);
        return wordsList;
    }

    public static List<Words> GetRandom(int flag, SqlSession sqlSession) {
        //        起始數
//        int base=(flag-1)*500;
        WordsMapper mapper = sqlSession.getMapper(WordsMapper.class);
        List<Words> wordsList = mapper.getWords(flag);
        Collections.shuffle(wordsList);

        return wordsList;
    }


}

MybatisUtils

package com.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author MoonLeaves
 * @purpose
 * @create 2020-10-27 15:44
 */
public class MybatisUtils {
    private  static SqlSessionFactory sqlSessionFactory = null;
    private  static InputStream inputStream = null;
    static {
        try {
            String resource = "MyEnglish1.0Config.xml";
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //    設定自動提交
    public static SqlSession getSqlSession(){
        return  sqlSessionFactory.openSession(true);
    }

}

StartTest

package com.utils;

import com.pojo.Words;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Scanner;

/**
 * @author MoonLeaves
 * @purpose 這個工具類是實際操作的類,不設定成static,為了資料的安全,只有在使用者密碼正確時才建立這個物件
 * @create 2020-10-28 18:57
 */
public class StartTest {
    public  void StartTestEnglish(int flag, SqlSession sqlSession,Scanner scanner){
        List<Words> wordsList=JudgeWords.GetRandom(flag,sqlSession);
        JudgeWords.testEnglish(wordsList,sqlSession,scanner);
    }
    public  void StartTestChinese(int flag, SqlSession sqlSession,Scanner scanner){
        List<Words> wordsList=JudgeWords.GetRandom(flag,sqlSession);
        JudgeWords.testChineseMeaning(wordsList,sqlSession,scanner);
    }
//    public void StartTestEnglishRandom(int flag, SqlSession sqlSession,Scanner scanner){
//        List<com.pojo.Words> wordsList=com.utils.JudgeWords.GetRandom(flag,sqlSession);
//    }

}

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myproject?useSSL=false
username=root
password=djq

MyEnglish1.0Config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--    利用properties-->
    <properties resource="db.properties"></properties>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        三種方式之一-->
        <package name="com.Mapper"/>
    </mappers>
</configuration>

pom.xml

<dependencies>
          <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/Java</directory>
                <excludes>
                    <exclude>**/*.java</exclude>
                </excludes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.* </include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.4.2</version>
                    <configuration>
                        <skipTests>true</skipTests>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>

    </build>

資料庫

見一個user表,words表
在這裡插入圖片描述

相關文章