循环回开始

本文关键字:开始 循环 | 更新日期: 2024-10-30 05:20:12

我正在为我的 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();
        }
    }
}

循环回开始

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();
        }
    }
}