我对OO编程还很陌生,我创建了一个简单的“猜数字”游戏,它可以正常运行。但是,尝试实现循环时会发生错误。更具体地说,我希望用户通过控制台重新启动程序(而不是再次编译并运行游戏)。
我需要有关静态void ExitGame()方法的帮助。此时,我正在研究“ RepL.it”,并且产生的错误如下:
main.cs(10,10):警告CS0649:字段GuessTheNumber.Game.replay' is never assigned to, and will always have its default value
为空”
编译成功-1个警告
欢迎来到猜谜游戏。请按Enter。
using System;
namespace GuessTheNumber
{
class Game
{
static int UserGuess;
static int Answer;
string replay;
static string EndProg = "No";
static void Main (string[] args)
{
Console.Title = "Guess the number.";
EntryMessage();
GenerateRandom();
while (EndProg == "No") {
askData();
}
}
static void EntryMessage()
{
Console.WriteLine("Welcome to the guessing game. Please press enter.");
Console.ReadLine();
}
public static void askData()
{
while (EndProg == "No")
{
Console.WriteLine(Answer);
Console.WriteLine("Guess a number between 1 and 100.");
UserGuess = Convert.ToInt32(Console.ReadLine());
WinLose();
}
askData();
}
public void askData(bool endProg)
{
Console.WriteLine("Does you want to play again");
if (replay == "y")//; Remove this semicolon
{
Console.WriteLine("\nOkay, guess again");
askData(EndProg == "No");
}
else if (replay == "n")//; Remove this semicolon
{
askData(EndProg == "Yes");
}
else
{
Console.ReadLine();
}
}
static void GenerateRandom()
{
Random random = new Random();
Answer = random.Next(0,101);
}
static void WinLose()
{
if (UserGuess == Answer)
{
Console.WriteLine("Correct number!");
EndProg="Yes";
}
else if (UserGuess > Answer)
{
Console.WriteLine("Too high.");
EndProg="No";
}
else if (UserGuess < Answer)
{
Console.WriteLine("Too Low.");
EndProg="No";
}
else
{
Console.WriteLine("Invalid answer.");
EndProg="No";
}
}
}
}
答案 0 :(得分:0)
您的代码中存在许多语法错误:
如果语句括号不应该加分号
else if (replay == "n");
应该是
else if (replay == "n")
您的askData()方法有时会被带一个布尔参数调用,但不需要一个
void askData()
应该是
void askData(bool endProg)
您正在混合和匹配静态和非静态方法,需要确定是在静态还是实例上下文中实现此逻辑
答案 1 :(得分:-1)
我相信罪魁祸首是您在if / else语句后使用分号:
static void ExitGame()
{
Console.WriteLine("Does you want to play again");
if (replay == "y")//; Remove this semicolon
{
Console.WriteLine("\nOkay, guess again");
askData(EndProg == "No");
}
else if (replay == "n")//; Remove this semicolon
{
askData(EndProg == "Yes");
}
else
{
Console.ReadLine();
}
}
那些分号将终止该语句,这将使Else If / Else块不跟随IF块,这在语法上是无效的。
这也解释了编译器正在生成的空语句警告。