---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------
面向对象版聊天机器人:
- 机器人有不同的名字,维护自己的FullLevel,可以SayHello,可以喂食(Feed),可以对它说话(Speak).
- 对异常情况(错误的喂饭数字,喂的太多撑死了)进行处理.
- 有两个机器人供选择,一开始通过数字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培训、期待与您交流! ----------------------