【发布时间】:2023-03-20 03:30:01
【问题描述】:
我正在尝试制作一个小型猜谜游戏,它会生成一个随机数,用户使用TextBox 和Button 输入一个数字。目前它正在创建随机数并做我想做的一切,但是每次用户按下按钮上的提交时,它都会生成一个新的随机数供他们猜测
我对 ASP.NET 类型的东西很陌生,所以我的代码可能效率低下且不正确,哈哈,所以我有两个特别的问题。
- 如何改进我的代码以使其更好地工作/完全正常工作。
- 我是否需要一个跑步者课程才能让它工作,我该怎么做?
public partial class WebPageSeparated : System.Web.UI.Page
{
private int randNum;
private int theirGuess;
public WebPageSeparated()
{
Random randomNum = new Random();
randNum = randomNum.Next(0, 10);
theirGuess = 0;
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Guessing game! Guess a number between [0,10) to see if you can get it right!";
new WebPageSeparated();
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
theirGuess = Convert.ToInt32(TextBox1.Text);
if (theirGuess != this.randNum)
{
Label1.Text = "Sorry, wrong number. Please try again!";
}
else if(theirGuess == this.randNum)
{
Label1.Text = "Correct! A new number has been generated, go ahead and try to do it again!";
new WebPageSeparated();
}
}
catch (System.FormatException)
{
Label1.Text = "Enter a number [1,10)";
}
}
}
【问题讨论】:
-
所以当他们点击提交时,它不会返回这两个响应之一?
-
@LucasKot-Zaniewski 确实如此,但是每次您提交新号码时,应该猜到的号码都会改变
-
第一步:不要使用异常来控制程序流程。
标签: c# asp.net postback viewstate page-lifecycle