黑马程序员_c#面向对象基础:聊天机器人

来源:互联网 发布:java界面美化 编辑:程序博客网 时间:2024/06/06 01:00

---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------

面向对象版聊天机器人:

  1. 机器人有不同的名字,维护自己的FullLevel,可以SayHello,可以喂食(Feed),可以对它说话(Speak).
  2. 对异常情况(错误的喂饭数字,喂的太多撑死了)进行处理.
  3. 有两个机器人供选择,一开始通过数字1,2选择聊天机器人.

代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace RobotChat

{

    class Program

    {

        static void Main(string[] args)

        {

            Robot robot1 = new Robot();

            robot1.Name = "I";

            robot1.Eat(5);

            Robot robot2 = new Robot();

            robot2.Name = "J";

            robot2.Eat(8);

            Console.WriteLine("请选择机器人: 1-->I; 2--> J");

            string str = Console.ReadLine();

 

            Robot robot=null;

            if (str == "1")

            {

                robot = robot1;//robot 指向了”robot1指向的对象.”

            }

            else if (str == "2")

            {

                robot = robot2;

            }

            else

            {

                Console.WriteLine("你要找的机器人不存在!");

                return;

            }

 

            robot.SayHello();

            while (true)

            {

                string strChat = Console.ReadLine();

                robot.Speak(strChat);

            }

 

            

 

        }

    }

    class Robot

    {

                               //属性

        public string Name

        {

            set;

            get;

        }

        private int FullLevel  //私有属性

        {

            set;

            get;

        }

                               //方法

        public void SayHello()

        {

            Console.WriteLine("¨:{0}",Name);

        }

        public void Eat(int foodCount)

        {

            if (FullLevel > 100)

            {

                return;

            }

            FullLevel += foodCount;

        }

        public void Speak(string str)

        {

            if (FullLevel <= 0)

            {

                Console.WriteLine("饿死了,不说了!");

                return;

            }

            if (str.Contains("姓名") || str.Contains("名字"))

            {

                this.SayHello(); //类的方法调用同类的另一个方法..

            }

            else if (str.Contains("女朋友"))

            {

                Console.WriteLine("年龄小,不考虑!");

            }

            else

            {

                Console.WriteLine("不好意思,听不懂!");

            }

            FullLevel--;

        }

    }

}

 

 

运行结果:

---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima/

原创粉丝点击