The realization of arithmetic in the first chapter of modern software engineering--stack implementation

Source: Internet
Author: User

Like Chiu, spend 20 minutes writing a command-line "software" that automatically generates the arithmetic of a primary school , satisfying each of the following requirements. The following requirements can be specified in the form of command-line arguments:

A) In addition to integers, support the arithmetic of true fractions. (Example: 1/6 + 1/8 = 7/24)

b) Allow the program to accept the user to enter the answer and determine the right and wrong. Finally, the total number of pairs/errors is given.

c) Gradually expand the functionality and the types of expressions that can be supported, and finally you want to support the following types of topics (up to 10 operators, the number of parentheses is unlimited):
25-3 * 4-2/2 + 89 =?
1/2 + 1/3-1/4 =?
(5-4) * (3 +28) =?


The implementation code is as follows:

Import Java.util.Stack;

Import Java.util.Scanner;
/**
* Using stacks to perform arithmetic classes
* Use two stacks to achieve operator precedence, a stack to hold the data to be computed Numstack, a to save the calculation of the priority character Pristack
*
* Basic algorithm implementation of the idea is: with the current obtained operator and Pristack stack top operator precedence: If higher than, then because the first operation, put into the top of the stack;
* If equal, because appear in the back, so will calculate after, so stack top element out of the stack, take out operand operation;
* If it is less than, then the same as the top element of the stack operation, the result into the operand stack. Each priority ' (' > ' * ' = '/' > ' + ' = '-' > ') '
*
*/
public class Operate {
Private stack<character> Pristack = new stack<character> ();//Operator stack
Private stack<integer> Numstack = new stack<integer> ();; /operand stacks

private static list = new ArrayList ();//For storing calculation answers
private static List List1 = new ArrayList ();//For storing the user input answer



//Generate True decimal form
public static String Zhen () {
int y = (int) (Math.random () * *) +1 ;//number of randomly generated operators
int[] w = new int[10];
String str =null;
if (y==1) {
Char ch = "+-". CharAt ((int) (Math.random () *));
for (int i=0;i< (2*y+2); i++) {
w[i]= (int) (Math.random () *9) +1;
}
str = w[0] + "/" + w[1] + ch + w[2] + "/" + w[3] + "=";
return str;
}
if (y==2) {
for (int i=0;i<2*y+2;i++) {
W[i] = (int) (Math.random () *9) +1;
}
Char ch1 = "+-". CharAt ((int) (Math.random () *));
Char CH2 = "+-". CharAt ((int) (Math.random () *));
str = w[0] + "/" + w[1] + ch1 + w[2] + "/" + w[3] + CH2 + w[4] + "/" + w[5] + "=";
return str;
}
if (y==3) {

}
return str;
}

Generating an integer expression
public static String Zhengshu () {
int y = (int) (Math.random () *) +2;//number of randomly generated operators
Int[] in = new INT[10];
String str =null;
Char ch1=0,ch2=0,ch3=0,ch4=0;
if (y==2) {
for (int i=0;i<y+1;i++) {
In[i] = (int) (Math.random () *30) +1;
}
int num = (int) (Math.random () *);
if (num==0) {//left Bracket
CH1 = "+-". CharAt ((int) (Math.random () *));
CH2 = "* *". CHARAT ((int) (Math.random () *));
str = "(" + in[0] + ch1 + in[1] + ")" + CH2 + in[2] + "=";
}else{
CH1 = "+-". CharAt ((int) (Math.random () *));
CH2 = "* *". CHARAT ((int) (Math.random () *));
str = in[0] + CH2 + "(" + in[1 "+ ch1 + in[2] +") "+" = ";
}
return str;
}
return str;
}


/**
* Pass in a string that needs to be parsed, return the result of the calculation (here because of the time problem, omitting the legitimacy validation)
* @param str requires a technical expression
* @return Calculation results
*/
public int caculate (String str) {
1. Determine if there are any illegal characters in the string
String temp;//used to temporarily hold the read character
2. The loop begins parsing the string, and when the string is parsed and the symbol stack is empty, the calculation is complete
StringBuffer tempnum = new StringBuffer ()//used for temporary storage of numeric strings (when multiple digits)
StringBuffer string = new StringBuffer (). append (str);//used to save, improve efficiency

while (String.Length ()! = 0) {
temp = string.substring (0, 1);
String.delete (0, 1);
Determine temp When temp is an action
if (!isnum (temp)) {
1. At this time the Tempnum is the number of operations required, take out the number, press stack, and empty tempnum
if (! "". Equals (Tempnum.tostring ())) {
When the first symbol of an expression is a parenthesis
int num = Integer.parseint (tempnum.tostring ());
Numstack.push (num);
Tempnum.delete (0, Tempnum.length ());
}
Precedence is compared with the currently obtained operator and the top of the stack: if it is above, it will be put into the top of the stack, if it is equal to, because it appears in the back, so it will be calculated after, so the stack top element out of the stack, take out the operand operation;
If it is less than, then the same as the top element of the stack operation, the result into the operand stack.

Determine the current operator and stack top element priority, take out the element, calculate (because the priority may be less than the top element of the stack, but also less than the second element, etc., need to use a loop to judge)
while (!compare (Temp.charat (0)) && (!pristack.empty ())) {
int a = (int) numstack.pop ();//second operand
int b = (int) numstack.pop ();//First operand
Char ope = Pristack.pop ();
int result = 0;//operation result
Switch (ope) {
If it is a plus or minus sign, then
Case ' + ':
result = B + A;
Put the result of the operation into the operand stack
Numstack.push (result);
Break
Case '-':
result = B-a;
Put the result of the operation into the operand stack
Numstack.push (result);
Break
Case ' * ':
result = b * A;
Put the result of the operation into the operand stack
Numstack.push (result);
Break
Case '/':
result = b/a;//The result of the operation into the operand stack
Numstack.push (result);
Break
}

}
Determines the current operator and the top element of the stack priority, if high, or lower than the level, after the calculation, the current operation symbol, put into the operator stack
if (Temp.charat (0)! = ' # ') {
Pristack.push (New Character (Temp.charat (0)));
if (Temp.charat (0) = = ') ') {//when the top of the stack is ' (', while the current element is ') ', it is enclosed in parentheses to finish, removing the parentheses
Pristack.pop ();
Pristack.pop ();
}
}
} else
When non-operational (number)
Tempnum = Tempnum.append (temp);//The number of readings to be read (when not single-digit)
}
return Numstack.pop ();
}

/**
* Determine if the incoming character is not a 0-9 number
*
* @param str
* Passed in string
* @return
*/
Private Boolean isnum (String temp) {
return Temp.matches ("[0-9]");
}

/**
* Compares the current operator with the top element operator priority, returns True if it is higher than the top element of the stack, otherwise returns false
*
* @param str needs to be compared with characters
* @return Comparison result true indicates higher precedence than top element, false represents lower precedence than top element of stack
*/
Private Boolean compare (char str) {
if (Pristack.empty ()) {
When empty, it is clear that the current priority is the lowest and returns a high
return true;
}
Char last = (char) pristack.lastelement ();
If the top of the stack is ' (' Obviously, the lowest priority, ') ' cannot be the top of the stack.
if (last = = ' (') {
return true;
}
Switch (str) {
Case ' # ':
Return false;//Terminator
Case ' (':
' (' highest priority, obviously returns true
return true;
Case ') ':
') ' has the lowest priority,
return false;
Case ' * ': {
' * * ' priority is only higher than ' +-'
if (last = = ' + ' | | last = = '-')
return true;
Else
return false;
}
Case '/': {
if (last = = ' + ' | | last = = '-')
return true;
Else
return false;
}
' +-' is the lowest and always returns false
Case ' + ':
return false;
Case '-':
return false;
}
return true;
}

public static void Main (String args[]) {
Operate Operate = new Operate ();

Scanner in = new Scanner (system.in);
for (int i=0;i<10;i++) {//Number of topics
int index = (int) (Math.random () *);
String str = NULL;
if (index = = 0) {
str = zhen ();

System.out.println (str);

int t = operate.caculate (str.substring (0, Str.length ()-1));

List.add (str);

}
if (index = = 1) {
str = Zhengshu ();

int t = operate.caculate (str.substring (0, Str.length ()-1));

List.add (str);
}
}

int t = 0;//correct number
int f =0;//Number of errors
for (int J =0;j<num;j++) {
if (in.next () = = "Done")
Break
if (List.get (j) ==in.next ()) {
t++;
}
Else
f++;
}
SYSTEM.OUT.PRINTLN ("Correct number of topics:" + t);
System.out.println ("Number of error questions:" + f);


}

}
}

The person who answered the question: Yang Yujie

The implementation of the first chapter of modern software engineering arithmetic--stack implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.