Multi-state computer program, multi-state computer
1. Create a form
2. Create an Operator class with two operands and a method
Public abstract class Operator {public abstract int Calc (); // Number of computations public int NumLeft {get; set;} public int NumRight {get; set ;}}
3. Create an Add class
public class Add:Operator { public override int Calc() { return this.NumLeft + this.NumRight; } }
4. Create a Sub class
public class Sub:Operator { public override int Calc() { return this.NumLeft - this.NumRight; } }
5. Create a Mul class
public class Mul:Operator { public override int Calc() { return this.NumLeft * this.NumRight; } }
6. Create a div class
Public class Div: Operator {public override int Calc () {int result = 0; if (NumLeft = 0) {throw new Exception ("the divisor cannot be 0 ");} else {result = this. numLeft/this. numRight;} return result ;}}
7. Create a class similar to a factory
Public class Factory {// static return value Type parameter public static Operator cu (string Type) {Operator = null; switch (Type) {case "+ ": break = new Add (); break; case "-": break = new Sub (); break; case "*": break = new Mul (); break; case "/": condition = new Div (); break;} return condition ;}}
8. Add
Private void btOk_Click (object sender, EventArgs e) {int num1 = Convert. toInt32 (txtLfet. text); string Signature = cb. text; int num2 = Convert. toInt32 (txtRight. text); // 04. call the static method of the Factory, input the type, and obtain the return value Operator part = Factory. cu (partial); part. numLeft = num1; part. numRight = num2; int result = 0; // 05. call the Calc () corresponding to the parent variable to complete the calculation and receive the return value try {result = part. calc ();} catch (Exception ex) {MessageBox. show (ex. message);} // 06. label1.Text = result is displayed in the Label. toString ();}