我正在尝试在C#中创建一个表单猜测游戏,它允许用户100猜测并计算他们错误的次数和他们正确的次数。我使用for循环尝试完成此操作,但是每次输入猜测时,一个计数器将等于1而另一个计数器将等于99.问题是它不会退出for循环而我无法弄清楚如何让它退出。
namespace Assignment10
{
public partial class Form1 : Form
{
Random random = new Random();
int[] rando = new int[100];
int answer;
int counter1 = 0;
int counter2 = 0;
int hoverNumber;
public Form1()
{
InitializeComponent();
start();
}
private void exitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void nextGuess_Click(object sender, EventArgs e)
{
guessButton.Enabled = true;
hoverBox.Text = "??";
}
public void start()
{
for (int x = 0; x < rando.Length; x++)
{
rando[x] = random.Next(0, 100);
hoverNumber = rando[x];
}
}
private void guessButton_Click(object sender, EventArgs e)
{
answer = Convert.ToInt32(GuessBox.Text);
for (int i = 0; i < rando.Length; ++i)
{
if (answer != rando[i])
counter1++;
else
counter2++;
for (int x = 0; x < 1; ++x)
{
if (answer != rando[i])
{
nextGuess.Enabled = true;
guessButton.Enabled = false;
label3.Text = "The number incorrect is: " + counter1;
GuessBox.Clear();
}
else if (answer == rando[i])
{
nextGuess.Enabled = true;
guessButton.Enabled = false;
label2.Text = "The number correct is: " + counter2;
GuessBox.Clear();
}
}
}
}
private void mouseLabel_MouseHover(object sender, EventArgs e)
{
hoverBox.Text = Convert.ToString(hoverNumber - 3);
}
}
}
答案 0 :(得分:0)
根据您的问题,问题可能在您的guessButton_Click
方法中,非常凌乱。我假设您只想将猜测与当前数字进行比较,而不是通过数组。每个号码猜1次吧?无论如何,因为你已经有正确和错误猜测数量的计数器,这简化了事情。只需检查counter1 + counter2
的数组索引的猜测,如下所示:
private void guessButton_Click(object sender, EventArgs e)
{
answer = Convert.ToInt32(GuessBox.Text);
if (answer == rando[counter1+counter2])
{
counter2++;
label2.Text = "The number of correct guesses is: " + counter2;
}
else (answer != rando[i])
{
counter1++;
label3.Text = "The number if incorrect guesses is: " + counter1;
}
nextGuess.Enabled = true;
guessButton.Enabled = false;
GuessBox.Clear();
}