Use the stack to calculate the expression application - give the children questions and calculate the positive answer rate (and save the data)

Keywords: PHP

(I) effect display

Item bank XX.txt

Answer process

Storage record file xx.txt

 

(2) encapsulate the required +, -, and other symbols, and then write several judgment methods

 1  public char[] op = {'+','-','*','/','(',')'};  
 2         public String[] strOp = {"+","-","*","/","(",")"};  
 3         public boolean isDigit(char c){  
 4             if(c>='0'&&c<='9'){  
 5                 return true;  
 6             }  
 7             return false;  
 8         }  
 9         public boolean isOp(char c){  
10             for(int i=0;i<op.length;i++){  
11                 if(op[i]==c){  
12                     return true;  
13                 }  
14             }  
15             return false;  
16         }  
17         public boolean isOp(String s){  
18             for(int i=0;i<strOp.length;i++){  
19                 if(strOp[i].equals(s)){  
20                     return true;  
21                 }  
22             }  
23             return false;  
24         }  

(3) because you need to convert all the questions to String type for processing, you need to process the calculation formula.

 1   public List<String> work(String str){  
 2             List<String> list = new ArrayList<String>();  
 3             char c;  
 4             
 5             //StringBuilder And StringBuffer It's essentially the same,Mainly StringBuilder Remove the cost of thread safety protection 
 6             //append()Method for character splicing
 7             StringBuilder sb = new StringBuilder();  
 8             for(int i=0;i<str.length();i++){  
 9                 c = str.charAt(i);  
10                 if(isDigit(c)){  
11                     sb.append(c);  
12                                }  
13                 if(isOp(c)){  
14                     if(sb.toString().length()>0){  
15                         list.add(sb.toString());  
16                         sb.delete(0, sb.toString().length());  
17                     }  
18                     //c+""In order to meet list<String>Storage parameters for String type
19                     list.add(c+"");  
20                 }  
21             }  
22             //Will last sb Data in to List Medium and empty sb
23             if(sb.toString().length()>0){  
24                 list.add(sb.toString());  
25                 sb.delete(0, sb.toString().length());  
26             }  
27             return list;  
28         }  
29         public void printList(List<String> list){  
30             for(String o:list){  
31                 System.out.print(o+" ");  
32             }  
33         }  

 

(4) convert infix expression to suffix expression, and then use stack to calculate

 

    public List<String> InfixToPostfix(List<String> list){  
            List<String> Postfixlist = new ArrayList<String>();//Store suffix expression  
            Stack<String> stack = new Stack<String>();//Staging operator  
            
            for(int i=0;i<list.size();i++){  
                
                
                  //Stack by priority 
                String s = list.get(i);  
                if(s.equals("(")){  
                    stack.push(s);  
                }else if(s.equals("*")||s.equals("/")){  
                    stack.push(s);  
                }else if(s.equals("+")||s.equals("-")){  
                    if(!stack.empty()){  
                        while(!(stack.peek().equals("("))){  
                            Postfixlist.add(stack.pop());  
                            if(stack.empty()){  
                                break;  
                            }  
                        }  
                        stack.push(s);  
                    }else{  
                        stack.push(s);  
                    }  
                }else if(s.equals(")")){  
                    while(!(stack.peek().equals("("))){  
                        Postfixlist.add(stack.pop());  
                    }  
                    stack.pop();  
                }else{  
                    Postfixlist.add(s);  
                }  
                if(i==list.size()-1){  
                    while(!stack.empty()){  
                        Postfixlist.add(stack.pop());  
                    }  
                }  
            }  
            return Postfixlist;  
        }  
        /** 
         * Suffix expression evaluation 
         */  
        public int doCal(List<String> list){  
            Stack<Integer> stack = new Stack<Integer>();  
            for(int i=0;i<list.size();i++){  
                String s = list.get(i);  
                int t=0;  
                if(!isOp(s)){  
                    t = Integer.parseInt(s);  
                    stack.push(t);  
                }else{  
                    if(s.equals("+")){  
                        int a1 = stack.pop();  
                        int a2 = stack.pop();  
                        int v = a2+a1;  
                        stack.push(v);  
                    }else if(s.equals("-")){  
                        int a1 = stack.pop();  
                        int a2 = stack.pop();  
                        int v = a2-a1;  
                        stack.push(v);  
                    }else if(s.equals("*")){  
                        int a1 = stack.pop();  
                        int a2 = stack.pop();  
                        int v = a2*a1;  
                        stack.push(v);  
                    }else if(s.equals("/")){  
                        int a1 = stack.pop();  
                        int a2 = stack.pop();  
                        int v = a2/a1;  
                        stack.push(v);  
                    }  
                }  
            }  
            return stack.pop();  
        }  

 

(V) methods for reading the contents of documents

 

 1     public String[] getFile(String pathName) throws Exception {
 2             // [1]Create one first File Body object of
 3             File file = new File(pathName);
 4             
 5             if (!file.exists())
 6                 throw new RuntimeException("cannot find file!");
 7             // [2]Load BUfferedReader flow
 8             BufferedReader br = new BufferedReader(new FileReader(file));
 9             String str;
10             String []arr = null;
11             // [3]Read line by line
12             while ((str = br.readLine()) != null) {
13 
14                 
15                 // The segmentation of data in files','Call the following split()function
16                  arr = str.split(",");
17 
18             }
19             return arr;
20         }

 

 

 

(VI) method of storing records in documents

        // Store data in a file
        public  void toFile(String path,int sumOfQ,String []wqs,int []Wresult,String TL,int []result,int[]arr) throws Exception {
            File file = null;
            FileWriter fWriter = null;
            file = new File(path);
            try {
                if (!file.exists()) {
                    System.out.println("The file to read in data does not exist");
                }
                fWriter = new FileWriter(file);
                fWriter.write("Number of questions:"+sumOfQ+"\n");
                fWriter.write("Corresponding topics:\n");
                for (int i = 0; i < sumOfQ; i++) {
                    fWriter.write(wqs[arr[i]]+"\n");
                }
                
                fWriter.write("Your submission at that time:  ");
                for (int i = 0; i < Wresult.length; i++) {
                    fWriter.write(Wresult[i]+" ");
                }
                fWriter.write("\n");
                
                fWriter.write("Positive answer rate of this question: "+TL+"\n");
                fWriter.write("Standard answer to this question: ");
                for (int i = 0; i < result.length; i++) {
                    fWriter.write(result[i]+" ");
                }
                fWriter.write("\n");
                fWriter.flush();

            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (fWriter != null) {
                    fWriter.close();
                }
            }

        }

(VII) compare the standard answer with the user's input answer, and calculate the positive answer rate

 1         // Method used to compare user's answer with standard answer
 2                     //Parameter is the answer array entered by the user
 3     public String compare(int[] a,int[] results,int sumOfQ) {
 4                         double t = 0;
 5                          //Save the serial number of the wrong question to list Easy to call
 6                         List<Integer> falseQ = new ArrayList<Integer>();
 7                         for (int i = 0; i < results.length; i++) {
 8                             if (a[i] == results[i])
 9                                 t++;
10                             else {
11 
12                                 falseQ.add(Integer.valueOf(i + 1));
13                             }
14                         }
15 
16                         if (falseQ.isEmpty()) {
17                             System.out.println("Congratulations, you have answered all the questions correctly!");
18                         } else {
19                             System.out.print("The answer is completed, and the serial number of the existing problems is:");
20                             for (int i = 0; i < falseQ.size(); i++) {
21                                 System.out.print(falseQ.get(i) + " ");
22                             }
23                         }
24                         System.out.println();
25                         System.out.println("Your positive response rate is:" + (DF_00(Double.valueOf(t / sumOfQ * 100))) + "%");
26 
27                         return String.valueOf(DF_00(Double.valueOf(t / sumOfQ * 100)))+"%";
28                     }

(8) methods for standardizing various data and calculation results

1         public static double DF_00(Double b) {
2             //call DecimalForamt The instance object of class specifies the number of bits of data.
3             //Because I have to operate the data after the specification is completed, and I will force it to be converted.
4         DecimalFormat dFormat = new DecimalFormat("#.00");
5         return        Double.parseDouble(dFormat.format(b));
6                     }    

 

(IX) methods for random questions

 

 1                     public int[] suiji(int sumOfQ,String[]wqs) {
 2 
 3                         int[] arr = new int[sumOfQ];
 4                         arr[0] = (int) (Math.floor(Math.random() * (wqs.length)));
 5                         boolean isSame = true;
 6                            int j=0;
 7                         while (isSame == true) {
 8 
 9                             int suiji = (int) (Math.floor(Math.random() * (wqs.length)));
10                             for (int i = 0; i < arr.length; i++) {
11                                 if (arr[i] == suiji) {
12                                     isSame = true;
13                                     break;
14                                 } else {
15                                     isSame = false;
16                                     continue;
17                                 }
18 
19                             }
20                             if (!isSame) {
21 
22                                 arr[j] = suiji;
23                                 j++;
24                                 isSame = true;
25                             }
26 
27                             if (j == 3) {
28                                 break;
29                             }
30                         }
31                         return arr;
32                     }                    

 

(x) methods for users to input and save answers

 

                    //It is used to let the user enter the answer and save the answer entered by the user.
                    public int [] Wresult(int sumOfQ) {
                        System.out.println("Please enter your answers in turn:");
                        Scanner sc = new Scanner(System.in);
                        String nextLine = sc.nextLine();

                        String[] temp = nextLine.split(" ");

                        int[] Wresult = new int[sumOfQ];

                        for (int i = 0; i < temp.length; i++) {
                            int wResult = Integer.parseInt(temp[i]);
                            Wresult[i] = wResult;
                        }
                        
                        
                        return Wresult;
                    }

 

(XI) test

 

 1     public static void main(String[] args) {
 2         // TODO Auto-generated method stub
 3 
 4         LV lt = new LV();
 5 
 6         // Get topic content
 7         try {
 8             wqs = lt.getFile("Data structure phase II.txt");
 9         } catch (Exception e) {
10             // TODO Auto-generated catch block
11             e.printStackTrace();
12         }
13 
14         System.out.println("Please enter the number of questions:");
15         Scanner scanner = new Scanner(System.in);
16         int sumOfQ = scanner.nextInt();
17         
18          arrs = lt.suiji(sumOfQ, wqs);
19          
20          
21          
22         results = new int[sumOfQ];
23         for (int i = 0; i < sumOfQ; i++) {
24             String str = wqs[arrs[i]];
25             System.out.println((i + 1) + ":      " + str);
26             List<String> list = lt.work(str);
27             List<String> list2 = lt.InfixToPostfix(list);
28             results[i] = lt.doCal(list2);
29         }
30 
31         
32         
33         int[] Wresult = lt.Wresult(sumOfQ);
34 
35         
36         String TL = lt.compare(results, Wresult, sumOfQ);
37         
38         
39         System.out.println("The correct answer is:");
40         for (int i = 0; i < results.length; i++) {
41             System.out.println((i + 1) + ":  " + results[i]);
42         }
43           
44     
45         System.out.println("This answer record is being stored for you. Please wait...");
46         Thread thread = new Thread();
47         
48         try {
49             lt.toFile("inputFile.txt", sumOfQ, wqs, Wresult, TL, results,arrs);
50         } catch (Exception e1) {
51             // TODO Auto-generated catch block
52             e1.printStackTrace();
53         }
54         
55         try {
56             Thread.sleep(1000);
57             thread.start();
58             System.out.println("Records stored in inputFile.txt!");
59         } catch (InterruptedException e) {
60             // TODO Auto-generated catch block
61             e.printStackTrace();
62         }
63         
64 
65     }

Posted by sactown on Sat, 02 Nov 2019 12:57:29 -0700