在调试器中,我已经验证了moveAmount在应该是时等于1,但是当我到达类中的if语句时,它会执行第二个if语句movementAmount为10.错误的'if'语句导致错误的结果
我的点对象,位置,最后加上一个额外的,所以Y坐标结果是11而不是10,我认为这可能是问题的一部分。
类:
public partial class Robot
{
public string direction = "north";
private Point position = new Point(0, 0);
private int movementAmount = 1;
public Robot() {}
public void moveRobot()
{
if (direction == "north" || direction == "North" & movementAmount == 1)
{
position.Y += movementAmount;
}
if (direction == "north" || direction == "North" & movementAmount == 10)
{
position.Y += movementAmount;
}
if (direction == "east" || direction == "East" & movementAmount == 1)
{
position.X += movementAmount;
}
if (direction == "east" || direction == "East" & movementAmount == 10)
{
position.X += movementAmount;
}
if (direction == "south" || direction == "South" & movementAmount == 1)
{
position.Y -= movementAmount;
}
if (direction == "south" || direction == "South" & movementAmount == 10)
{
position.Y -= movementAmount;
}
if (direction == "west" || direction == "West" & movementAmount == 1)
{
position.X -= movementAmount;
}
if (direction == "west" || direction == "West" & movementAmount == 10)
{
position.X -= movementAmount;
}
}
public Point Position
{
get
{
return position;
}
}
public int MovementAmount
{
get
{
return movementAmount;
}
set
{
movementAmount = value;
if (movementAmount != 1 & movementAmount != 10)
{
throw new ArgumentOutOfRangeException("Must be 1 or 10");
}
}
}
}
}
主程序:
public partial class frmSimpleRobot : Form
{
public frmSimpleRobot()
{
InitializeComponent();
}
Robot arrow = new Robot();
private void btnGoOne_Click(object sender, EventArgs e)
{
arrow.MovementAmount = 1;
}
private void btnGoTen_Click(object sender, EventArgs e)
{
arrow.MovementAmount = 10;
}
private void btnNorth_Click(object sender, EventArgs e)
{
arrow.direction = "north";
arrow.moveRobot();
lblRobotPos.Text = "(X=" + arrow.Position.X.ToString() + ", " + "Y=" + arrow.Position.Y.ToString() + ")";
}
private void btnEast_Click(object sender, EventArgs e)
{
arrow.direction = "east";
arrow.moveRobot();
lblRobotPos.Text = "(X=" + arrow.Position.X.ToString() + ", " + "Y=" + arrow.Position.Y.ToString() + ")";
}
private void btnSouth_Click(object sender, EventArgs e)
{
arrow.direction = "south";
arrow.moveRobot();
lblRobotPos.Text = "(X=" + arrow.Position.X.ToString() + ", " + "Y=" + arrow.Position.Y.ToString() + ")";
}
private void btnWest_Click(object sender, EventArgs e)
{
arrow.direction = "west";
arrow.moveRobot();
lblRobotPos.Text = "(X=" + arrow.Position.X.ToString() + ", " + "Y=" + arrow.Position.Y.ToString() + ")";
}
}
}
援助吗?
当'direction =='north''时,'movementAmount'的值不会有太大影响。使用'()' – 2014-12-07 00:14:11
@AlexBell:“方向==”北方“**”和“方向==”北方“”如何都是真的? – 2014-12-07 00:15:58
最好的方法是使用'else if'或'switch'语句,如下所示。问候, – 2014-12-07 00:20:39