c# - C#中的连续循环
问题描述
我最近开始学习 C#,并开始根据有关笑话的流程图 ( http://prntscr.com/jo656t ) 制作简单的程序。
然而,当我在“你想听另一个笑话吗?”的流程图中时。我完全不知道如何循环这个。
这是代码。
class Program
{
static void Main(string[] args)
{
Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
string Name;
Console.WriteLine("What is your name? ");
Name = Console.ReadLine();
Console.Write(Name);
Console.Clear();
Console.WriteLine("What is your age?");
int Age = Convert.ToInt16(Console.ReadLine());
Console.Write(Age);
Console.Clear();
string[] jokes = new string[] { "Joke1", "Joke2", "Joke3", "Joke4" };
int upper = jokes.GetUpperBound(0);
int lower = jokes.GetLowerBound(0);
Random rnd = new Random();
int jk = rnd.Next(lower, upper + 1);
if (Age >= 16)
{
Console.WriteLine("Do you want to hear a joke?");
string option = Console.ReadLine();
if (option == "yes")
{
Console.WriteLine(jokes[jk]);
Console.Read();
Console.WriteLine("Do you want to hear another joke?");
string option2 = Console.ReadLine();
int i;
if (option2 == "yes")
{
i = 0;
}
else
{
i = 1;
}
do
{
Console.WriteLine(jokes[jk]);
Console.Read();
} while (i == 0);
}
else
{
Console.WriteLine("Have a nice day, " + Name);
Console.Read();
}
}
else
{
Console.WriteLine("What a pitty! You're too young to hear this joke!");
Console.Read();
Console.WriteLine("Have a nice day, " + Age);
}
}
我不知道,因为我完全被困在这一点上,我们将不胜感激。
提前致谢!
解决方案
就我个人而言,我会尝试重写代码,使其更具可读性,但这样的事情应该可以工作:
bool keepTellingJokes = true;
while (keepTellingJokes)
{
// your joke code here
Console.WriteLine("Do you want to hear another joke?");
string option2 = Console.ReadLine();
// break out of loop
if (option2 == "no")
{
keepTellingJokes = false;
}
}
// code after escaping joke loop
免责声明:我不是每天都写 c#。
推荐阅读
- python - 对迭代中具有重复元素的字符串进行分区
- scala - 如何在 Akka Typed 中从 ActorSystem 传递自我引用
- javascript - 如何在同一行中创建左对齐按钮、居中对齐文本和右对齐按钮(ReactJS)
- r - 对不同的正态分布进行积分得到 0 概率
- gnuplot - 带有 gnuplot 的 4D 绘图
- javascript - 定义一个值在 1 到 100 之间的变量
- angular - 是否可以选择一个文件夹并以角度 9 上传其中的所有文件?
- c++ - 如何将 C++ 系统调用连接到 freertos
- c++ - 向量的内存位置不连续
- php - 尝试在 Arch 上升级 DokuWiki 农场设置,wiki 现在完全被冲洗