我正在尝试了解根据我的书(Head first into C #,3.5版)编写的代码。我对我应该编写的循环完全感到困惑。这是我应该做的:
制作一个表单,有一个按钮,复选框和标签。只有当选中复选框时,才会在按下按钮时更改标签的背景颜色。颜色在按下按钮时应在红色和蓝色之间切换。
这是我的当前代码。
namespace SecondColorChangingWindow
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
while (checkBox1.Checked == false) // The code will stop if the box isn't checked
{
MessageBox.Show("You need the check box checked first!");
break;//Stops the infinite loop
}
while (checkBox1.Checked == true)// The code continues "if" the box is checked.
{
bool isRed = false; // Makes "isRed" true, since the background color is default to red.
if (isRed == true) // If the back ground color is red, this will change it to blue
{
label1.BackColor = Color.Blue; // changes the background color to blue
isRed = false; //Makes "isRed" false so that the next time a check is made, it skips this while loop
MessageBox.Show("The color is blue.");//Stops the program so I can see the color change
}
if (isRed == false)//if the back ground color is blue, this will change it to red
{
label1.BackColor = Color.Red;//Makes the background color red
isRed = true;//Sets the "isRed" to true
MessageBox.Show("The color is red.");//Stops the program so I can see the color change.
}
}
}
}
}
现在它只会循环红色。我不明白我做错了什么。这不是我写的第一段代码。我从整数到布尔值尝试改变颜色,但要么只能让颜色变一次,要么程序无限循环而卡住。