星期二

发布时间 2023-09-27 00:24:28作者: umiQa

用二维数组实现了四则运算的出题

这是主类

import javax.swing.*;
import javax.swing.text.MaskFormatter;
import java.io.*;
import java.util.Random;
import java.util.Scanner;


public class MathCalculate {
    public static int MAXSIZE=10000;
    private int optionNum=10;
    private int length=30;
    private int base=0;
    private int Size=100;
    public static int count=0;
    public int[][] errorNum=new int[optionNum][MAXSIZE];
    public int[][] errorSym=new int[optionNum-1][MAXSIZE];
    public int[] errorRe=new int[MAXSIZE];
    public int[][] errorSymb=new int[optionNum-1][MAXSIZE];
    public int l=0;
    public int[] errorCount=new int[MAXSIZE];
    public int[][] number=new int[optionNum][MAXSIZE];
    public int[][] symbol=new int[optionNum-1][MAXSIZE];
    public int[] result=new int[MAXSIZE];
    public int[][] symbolBracket=new int[optionNum-1][MAXSIZE];   //符号括号真值
    private Random random=new Random();
    private Scanner sc=new Scanner(System.in);


    public MathCalculate() throws FileNotFoundException {
    }

    public int[][] randomSym()
    {
        int a[][]=new int[optionNum-1][MAXSIZE];
        for(int i=0;i<optionNum-1;i++)
        {
            for(int j=0;j<length;j++)
            {
                a[i][j]=random.nextInt(4)+1;
            }
        }
        return a;
    }
    public int[][] randomBracket()
    {
        int a[][]=new int[optionNum-1][MAXSIZE];
        for(int j=0;j<length;j++)
        {
            for(int i=0;i<optionNum-1;i++)
            {
                if(i>0&&a[i-1][j]==1)
                    a[i][j]=0;
                else
                    a[i][j]=random.nextInt(2);
            }
        }
        return a;
    }
    public File file=new File("src\\Mistakes.txt");

    public void CreatCal()
    {
        String ss;
        System.out.println("请输入题数:");
        length=sc.nextInt();
        System.out.println("请输入操作数:");
        optionNum=sc.nextInt();
        System.out.println("请输入操作数范围下限:");
        base=sc.nextInt();
        System.out.println("请输入操作数上限:");
        Size=sc.nextInt();
        System.out.println("请输入是否有括号 Y/N");
        ss=sc.next();
        if(ss.equals("Y"))
            symbolBracket=randomBracket();
        else
            for(int i=0;i<optionNum-1;i++)
            {
                for(int j=0;j<length;j++)
                {
                    symbolBracket[i][j]=0;
                }
            }
        symbol=randomSym();
        for(int j=0;j<length;j++)
        {
            for(int i=0;i<optionNum;i++)
            {
                number[i][j]=random.nextInt(Size)+base;
            }
            getResult(getFormula(j),j);
            while(ArrayStack.y==0) {
                for (int k = 0; k < optionNum; k++) {
                    number[k][j] = random.nextInt(Size) + base;
                }
                ArrayStack.y=1;
                getResult(getFormula(j),j);
            }
        }
        for(int j=0;j<length;j++)
        {
            getResult(getFormula(j),j);
        }
    }
    public void CreatCal(int op,int ba,int sz,boolean ss) {
        System.out.println("输入题数:");
        length = sc.nextInt();
        optionNum = op;
        base = ba;
        Size = sz;
        if (ss)
            symbolBracket = randomBracket();
        else
            for(int i=0;i<optionNum-1;i++)
            {
                for(int j=0;j<length;j++)
                {
                    symbolBracket[i][j]=0;
                }
            }
        symbol = randomSym();
        for (int j = 0; j < length; j++) {
            for (int i = 0; i < optionNum; i++) {
                number[i][j] = random.nextInt(Size) + base;
            }
            getResult(getFormula(j), j);
            while (ArrayStack.y == 0) {
                for (int k = 0; k < optionNum; k++) {
                    number[k][j] = random.nextInt(Size) + base;
                }
                ArrayStack.y = 1;
                getResult(getFormula(j), j);
            }
            getResult(getFormula(j), j);
        }
    }
    public void FileWrite() throws IOException {
                FileWriter f=null;
                BufferedWriter f1=null;

                try {
                    f=new FileWriter("src\\Mistakes.txt");
                    f1=new BufferedWriter(f);
                    for (int i = 0; i < length; i++) {
                        f1.write(getFormula(i)+"=       ");//把String中的字符写入文件
                        if(i%3==2)
                        f1.newLine();//换行操作
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }finally {//如果没有catch 异常,程序最终会执行到这里
                    try {
                        f1.close();
                        f.close();//关闭文件
                    } catch (Exception e2) {
                        // TODO: handle exception
                    }
                }
                Start();
    }
    public void Answer() throws IOException {
        for(int j=0;j<length;j++)
        {
            int a;
            System.out.println(j+1+" "+getFormula(j)+"=");
            a=sc.nextInt();
            if(a==result[j])
            {
                count++;
                System.out.println("回答正确");
            }
            else
            {
                System.out.println("回答错误");
                System.out.println("答案:"+result[j]);
                for(int i=0;i<optionNum-1;i++)
                {
                    errorNum[i][l]=number[i][j];
                    errorSym[i][l]=symbol[i][j];
                    errorSymb[i][l]=symbolBracket[i][j];
                    if(i==optionNum-2)
                        errorNum[i+1][l]=number[i+1][j];
                }
                errorCount[l]=1;
                errorRe[l]= result[j];
                l++;
            }
        }
        System.out.println("正确率:"+String.format("%.2f", count/(double)length*100).toString()+"%");
        Start();
    }
    public String getSymbols(int s)
    {
        String sb="";
        switch (s)
        {
            case 1:
                sb+="+";
                break;
            case 2:
                sb+="-";
                break;
            case 3:
                sb+="*";
                break;
            case 4:
                sb+="/";
                break;
        }
        return sb;
    }
    public String getFormula(int j)
    {
        String formula="";
        for(int i=0;i<optionNum-1;i++)
        {
            if(i==0&&symbolBracket[i][j]==1)
                formula+="(";
            formula+=number[i][j];
            if(i!=0&&symbolBracket[i-1][j]==1)
                formula+=")";
            formula+=getSymbols(symbol[i][j]);
            if(i!=optionNum-2&&symbolBracket[i+1][j]==1)
                formula+="(";
            if(i==optionNum-2)
                formula+=number[i+1][j];
            if(i==optionNum-2&&symbolBracket[i][j]==1)
                formula+=")";
        }
        return formula;
    }    //获得表达式
    public String getErrorFormula(int j)
    {
        String formula="";
        for(int i=0;i<optionNum-1;i++)
        {
            if(i==0&&errorSymb[i][j]==1)
                formula+="(";
            formula+=errorNum[i][j];
            if(i!=0&&errorSymb[i-1][j]==1)
                formula+=")";
            formula+=getSymbols(errorSym[i][j]);
            if(i!=optionNum-2&&errorSymb[i+1][j]==1)
                formula+="(";
            if(i==optionNum-2)
                formula+=errorNum[i+1][j];
            if(i==optionNum-2&&errorSymb[i][j]==1)
                formula+=")";
        }
        return formula;
    }
    public void getResult(String expression,int j)
    {
        {
            //创建两个栈,数栈,一个符号栈
            ArrayStack numStack = new ArrayStack(1000);
            ArrayStack operStack = new ArrayStack(1000);
            //定义需要的相关变量
            int index = 0;
            int num1 = 0;
            int num2 = 0;
            int oper = 0;
            int res = 0;
            char ch = ' '; //将每次扫描得到char保存到ch
            String keepNum = ""; //用于拼接 多位数
            //开始while循环的扫描expression
            while(true) {
                //依次得到expression 的每一个字符
                ch = expression.substring(index, index+1).charAt(0);
                //判断ch是什么,然后做相应的处理
                if(operStack.isOper(ch)) {//如果是运算符
                    //判断当前的符号栈是否为空
                    if(!operStack.isEmpty()) {
                        //如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符,就需要从数栈中pop出两个数,
                        //这里需要判断是否此时的栈顶是否为左括号,如果是左括号不进入此循环
                        //我们设定的左括号是优先级大于加减乘除,所以当发现下一个进栈的符号的优先级比此时的栈顶的左括号优先级小的时候,
                        //应该让符号直接进栈,不进行弹出左符号的运算(左括号弹出来运算是不行的)
                        if(operStack.priority(ch) <= operStack.priority(operStack.peek()) & operStack.peek()!=40) {
                            num1 = numStack.pop();
                            num2 = numStack.pop();
                            oper = operStack.pop();
                            res = numStack.cal(num1, num2, oper);
                            //把运算的结果如数栈
                            numStack.push(res);
                            //然后将当前的操作符入符号栈
                            operStack.push(ch);
                            /**
                             * 进行右括号的判断。匹配左括号
                             * 当发现进入的是右括号时就优先进行括号内的计算
                             */
                        } else if(ch==41){
                            //先让右括号进栈
                            operStack.push(ch);
                            if (ch==41) {
                                //再把右括号弹出
                                int oper1 = operStack.pop();
                                //弹出右括号后开始进行括号内运算
                                while(true) {
                                    //右括号
                                    num1 = numStack.pop();
                                    num2 = numStack.pop();
                                    oper = operStack.pop();
                                    res = numStack.cal(num1, num2, oper);
                                    //把运算的结果如数栈
                                    numStack.push(res);
                                    //当运算到栈顶符号为左括号时候,就弹出栈顶元素左括号,结束循环
                                    if(operStack.peek()==40) {
                                        int oper2 = operStack.pop();
                                        break;
                                    }
                                }

                            }

                            //如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈.
                        }
                        else {
                            operStack.push(ch);
                        }
                    }else {
                        //如果为空直接入符号栈
                        operStack.push(ch);
                    }
                } else { //如果是数,则直接入数栈

                    //分析思路
                    //1. 当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
                    //2. 在处理数,需要向expression的表达式的index 后再看一位,如果是数就进行扫描,如果是符号才入栈
                    //3. 因此我们需要定义一个变量 字符串,用于拼接

                    //处理多位数
                    keepNum += ch;

                    //如果ch已经是expression的最后一位,就直接入栈
                    if (index == expression.length() - 1) {
                        numStack.push(Integer.parseInt(keepNum));
                    }else{

                        //判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈
                        //注意是看后一位,不是index++
                        if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
                            //如果后一位是运算符,则入栈 keepNum = "1" 或者 "123"
                            numStack.push(Integer.parseInt(keepNum));
                            //重要的!!!!!!, keepNum清空
                            keepNum = "";

                        }
                    }
                }
                //让index + 1, 并判断是否扫描到expression最后.
                index++;
                if (index >= expression.length()) {
                    break;
                }
            }

            //当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行.
            while(true) {
                //System.out.println(operStack.peek());
                //如果符号栈为空,则计算到最后的结果, 数栈中只有一个数字【结果】
                if(operStack.isEmpty()) {
                    break;
                }
                num1 = numStack.pop();
                num2 = numStack.pop();
                oper = operStack.pop();
                res = numStack.cal(num1, num2, oper);
                numStack.push(res);//入栈

            }
            //将数栈的最后数,pop出,就是结果
            int res2 = numStack.pop();
            result[j]=res2;
        }
    }
    public void errorBook() throws IOException {
        for(int j=0;j<l;j++)
        {
            System.out.println(j+1+" "+getErrorFormula(j)+"="+"            错误次数:"+errorCount[j]);
        }
        String ss="";
        int num;
        System.out.println("是否重做Y/N");
        ss=sc.next();
        int k=0;
        count=0;
        int aa=l;
        if(ss.equals("Y"))
        for(int j=0;j<l;j++)
        {
            System.out.println(j+1+" "+getErrorFormula(j)+"=");
            num=sc.nextInt();
            if(num==errorRe[j])
            {
                count++;
                System.out.println("回答正确");
            }
            else {
                System.out.println("回答错误");
                System.out.println("答案:"+errorRe[j]);
                for (int i = 0; i < optionNum - 1; i++) {
                    errorNum[i][k] = number[i][j];
                    errorSym[i][k] = symbol[i][j];
                    errorSymb[i][k] = symbolBracket[i][j];
                    if (i == optionNum - 2)
                        errorNum[i + 1][k] = number[i + 1][j];
                    errorRe[k] = result[j];
                }
                errorCount[k]=errorCount[j];
                errorCount[k]++;
                k++;
            }
        }
        l=k;
        System.out.println("正确率:"+String.format("%.2f", count/(double)aa*100).toString()+"%");
        Start();
    }
    public void Start() throws IOException {
        Scanner sc=new Scanner(System.in);
        System.out.println("-----------------------");
        System.out.println("1.小学二年级");
        System.out.println("2.小学三年级");
        System.out.println("3.小学四年级");
        System.out.println("4.自定义");
        System.out.println("5.错题统计重做");
        System.out.println("6.文件导入");
        System.out.println("-----------------------");
        int sw;
        sw=sc.nextInt();
        switch (sw)
        {
            case 1:
                CreatCal(2,0,100,false);
                Answer();
                break;
            case 2:
                CreatCal(4,0,100,false);
                Answer();
                break;
            case 3:
                CreatCal(5,0,100,true);
                Answer();
                break;
            case 4:
                CreatCal();
                Answer();
                break;
            case 5:
                errorBook();
                break;
            case 6:
                FileWrite();
                break;
        }
    }
}

  这是栈类,用来计算结果

//先创建一个栈,直接使用前面创建好
//定义一个 ArrayStack 表示栈, 需要扩展功能
class ArrayStack {
    private int maxSize; // 栈的大小
    private int[] stack; // 数组,数组模拟栈,数据就放在该数组
    private int top = -1;// top表示栈顶,初始化为-1

    //构造器
    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //增加一个方法,可以返回当前栈顶的值, 但是不是真正的pop
    public int peek() {
        return stack[top];
    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }
    //栈空
    public boolean isEmpty() {
        return top == -1;
    }
    //入栈-push
    public void push(int value) {
        //先判断栈是否满
        if(isFull()) {
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }
    //出栈-pop, 将栈顶的数据返回
    public int pop() {
        //先判断栈是否空
        if(isEmpty()) {
            //抛出异常
            throw new RuntimeException("栈空,没有数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }
    //显示栈的情况[遍历栈], 遍历时,需要从栈顶开始显示数据
    public void list() {
        if(isEmpty()) {
            System.out.println("栈空,没有数据~~");
            return;
        }
        //需要从栈顶开始显示数据
        for(int i = top; i >= 0 ; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
    //返回运算符的优先级,优先级是程序员来确定, 优先级使用数字表示
    //数字越大,则优先级就越高.
    public int priority(int oper) {
        if(oper=='(' || oper==')') {
            return 2;
        }else if(oper == '*' || oper == '/'){
            return 1;
        } else if (oper == '+' || oper == '-') {
            return 0;
        } else {
            return -1; // 假定目前的表达式只有 (),+, - , * , /
        }
    }
    //判断是不是一个运算符
    public boolean isOper(char val) {
        return val == '+' || val == '-' || val == '*' || val == '/'|| val=='('||val==')';
    }
    public static int y=1;
    //计算方法
    public int cal(int num1, int num2, int oper) {
        int res = 0; // res 用于存放计算的结果
        switch (oper) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;// 注意顺序
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                if(num1==0)
                {
                    y=0;
                    break;
                }
                else if(num2%num1!=0)
                {
                    y=0;
                }
                else
                    res = num2 / num1;

                break;
            default:
                break;
        }
        return res;
    }

}