我正在为我的CIT类构建这个程序,并希望在正确猜出数字的情况下让它环回并创建一个新的数字。我阅读了我的教科书中涵盖这一部分的部分,但我对如何添加此内容以及确切位置感到困惑。
以下是我现在的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Guess_My_Number
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int number;
private void Form1_Load(object sender, EventArgs e)
{
// Generate the number.
Random generator = new Random();
number = generator.Next(0, 100);
MessageBox.Show("Can you guess the number I am thinking of
between 1 and 100?");
}
private void guessButton_Click(object sender, EventArgs e)
{
// Get the guess from the textbox.
int guess = Convert.ToInt32(guessTextbox.Text);
// Check if the number is right.
if (guess > number)
{
MessageBox.Show("Too high, try again.");
}
if (guess < number)
{
MessageBox.Show("Too low, try again.");
}
if (guess == number)
{
MessageBox.Show("Congratulations, you guessed my number!");
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Clost the program.
this.Close();
}
}
}
答案 0 :(得分:5)
namespace Guess_My_Number
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int number;
Random generator = new Random();
private void Form1_Load(object sender, EventArgs e)
{
GenerateNewNumber();
}
private void GenerateNewNumber()
{
number = generator.Next(0, 100);
MessageBox.Show("Can you guess the number I am thinking of
between 1 and 100?");
}
private void guessButton_Click(object sender, EventArgs e)
{
// Get the guess from the textbox.
int guess = Convert.ToInt32(guessTextbox.Text);
// Check if the number is right.
if (guess > number)
{
MessageBox.Show("Too high, try again.");
}
if (guess < number)
{
MessageBox.Show("Too low, try again.");
}
if (guess == number)
{
MessageBox.Show("Congratulations, you guessed my number!");
GenerateNewNumber();
}
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}