- <font size="4">using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace 用面向对象做计算器
- {
- class Program
- {
- //全局变量
- public static int numBer1;
- public static string sign;
- public static int numBer2;
- static void Main(string[] args)
- {
- //用面向对象写计算器
- //封装,继承,多态
- while (true)
- {
- try
- {
- Console.WriteLine("请您输入数字");
- numBer1 = Convert.ToInt32(Console.ReadLine()); //第一个数字
- }
- catch
- {
- Console.WriteLine("您输入的数字错误,请重新输入");
- numBer1 = Convert.ToInt32(Console.ReadLine()); //第一个数字
- }
- try
- {
- Console.WriteLine("请您输入字符");
- sign = Console.ReadLine(); //字符
- }
- catch
- {
- Console.WriteLine("您输入的字符错误,请重新输入");
- sign = Console.ReadLine();
- }
- try
- {
- Console.WriteLine("请您输入数字");
- numBer2 = Convert.ToInt32(Console.ReadLine()); //第二个数字
- break;
- }
- catch
- {
- Console.WriteLine("您输入的数字错误,请重新输入");
- numBer2 = Convert.ToInt32(Console.ReadLine()); //第二个数字
- }
- }
- //继承+方法名一样
- Count count = new Count(); //遍历父类
- switch (sign)
- {
- case "+": count = new Add(); //赋值给父类
- break;
- case "-": count = new Reduce();
- break;
- case "*": count = new Ride();
- break;
- case "/": count = new Divide();
- break;
- }
- //Add add = new Add();
- //Count count = add;
- //计算
- int output = 0;
- output = count.UseCount(numBer1, numBer2);
- Console.WriteLine("{0}{1}{2}={3}", numBer1, sign, numBer2, output);
- Console.ReadKey();
- }
- }
- //父类
- class Count
- {
- public virtual int UseCount(int number1, int number2)
- {
- return 0;
- }
- }
- //加子类
- class Add : Count
- {
- public override int UseCount(int number1, int number2)
- {
- return (number1 + number2);
- }
- }
- //减子类
- class Reduce : Count
- {
- public override int UseCount(int number1, int number2)
- {
- return (number1 - number2);
- }
- }
- //乘类
- class Ride : Count
- {
- public override int UseCount(int number1, int number2)
- {
- return (number1 * number2);
- }
- }
- //除类
- class Divide : Count
- {
- public override int UseCount(int number1, int number2)
- {
- return (number1 / number2);
- }
- }
- }
- </font>
复制代码 |