namespace Game
{
public partial class Form2 : Form
{
String[] word = { "Ordinary", "Darkness", "Marriage" };
Random rnd = new Random();
public Form2()
{
InitializeComponent();
label1.Text = word[rnd.Next(0, word.Length)];
}
private void button1_Click(object sender, EventArgs e)
{
string guess;
guess = textBox1.Text;
while (guess != label1.Text)
{
if (guess != label1.Text)
MessageBox.Show("You got it right");
else
MessageBox.Show("You got it wrong");
}
}
當我輸入一個錯誤的單詞時,它會掉到 else 后面,之后的表單將不會在標簽上顯示該單詞。我對 c# 很陌生,請發送幫助。
uj5u.com熱心網友回復:
首先,這個邏輯是錯誤的:
if (guess != label1.Text)
{
MessageBox.Show("You got it right");
}
else
MessageBox.Show("You got it wrong");
比較運算子應該是==. 否則這將是一個非常簡單的游戲(從字面上猜測任何與目標字串不匹配的字串)。
一旦你糾正了這個,考慮你在這里做什么:
while (guess != label1.Text)
{
if (guess == label1.Text)
{
MessageBox.Show("You got it right");
}
else
MessageBox.Show("You got it wrong");
}
那么,如果猜測不正確,這里會發生什么?回圈繼續,一遍又一遍,無限。所以程式本質上“鎖定”并變得無回應,因為邏輯忙于無限回圈一個在該回圈中永遠不會改變的條件。
退一步......你為什么會有這個回圈?您在此按鈕單擊處理程式中要做的就是檢查答案,因此只需檢查答案:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == label1.Text)
MessageBox.Show("You got it right");
else
MessageBox.Show("You got it wrong");
}
根本不需要回圈,因為沒有重復操作。每當單擊按鈕時,此邏輯都將被重新呼叫。
uj5u.com熱心網友回復:
整個 while 回圈對我來說沒有多大意義,因為檢查似乎有點奇怪。難道你不想檢查猜測是否等于標簽,如果不顯示“你在螢屏上弄錯了”,你真的不需要整個事情的一段時間。
if (guess == label1.Text)
{
MessageBox.Show("You got it right");
}
else
{
MessageBox.Show("You got it wrong");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332896.html
