问题描述
我对OO编程还很陌生,我创建了一个简单的猜数字"游戏,它可以正常运行.但是,尝试实现循环时会发生错误.更具体地说,我希望用户通过控制台重新启动程序(而不是再次编译并运行游戏).
I am fairly new to OO programming, I have created a simple "Guess the number" game, it functions correctly. However, when attempting to implement a loop errors occur. More specifically, I want the user to restart the program through a console [not compiling and running the game again].
我需要有关静态void ExitGame()方法的帮助.此时,我正在研究"RepL.it",并且产生的错误如下:
I need help with the static void ExitGame() method. At this moment in time, I am working on "RepL.it" and the generated errors are as followed:
main.cs(10,10):警告CS0649:字段GuessTheNumber.Game.replay' is never assigned to, and will always have its default value
null'编译成功-1个警告欢迎来到猜谜游戏.请按Enter.
main.cs (10,10): warning CS0649: Field GuessTheNumber.Game.replay' is never assigned to, and will always have its default value
null'Compilation succeeded - 1 warning (s)Welcome to the guessing game. Please press 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";
}
}
}
}
推荐答案
您的代码中存在许多语法错误:
There's a number of syntactical errors in your code:
-
如果语句括号不应以分号后缀
If statement parentheses shouldn't be suffixed with a semicolon
else if (replay == "n");
应该是
else if (replay == "n")
您的askData()方法有时会被带一个布尔参数调用,但不需要一个
Your askData() method is sometimes being called with a bool argument but doesn't take one
void askData()
应该是
void askData(bool endProg)
您正在混合和匹配静态和非静态方法,需要确定是在静态还是实例上下文中实现此逻辑
You are mixing and matching static and non-static methods and need to decide whether to implement this logic in a static or instance context
这篇关于我的程序中集成循环出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!