我最近开始研究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);
}
}
我不知道,因为我完全陷入困境,所以我们将不胜感激。
提前致谢!
答案 0 :(得分:1)
就个人而言,我会尝试重写代码,使其更具可读性,但这样的事情应该有效:
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#。
答案 1 :(得分:0)
该流程图可以细分为三个主要部分:
中间部分(从msgbox "joke()"
到msgbox "would you like to hear another joke?"
)使用do
/ while
循环进行编码。将它作为一个单独的方法是有用的:
private static void TellJokes() {
bool shouldContinue;
do {
shouldContinue = true;
... // Tell a joke, ask if they liked it, and ask if they want more
if (answer == "no") {
shouldContinue = false;
}
} while (shouldContinue);
}
请注意,您可以将"Have a nice day!"
的打印移动到程序的底部,因为无论如何所有分支都会打印出来。
答案 2 :(得分:0)
你可以这样做
Random rnd = new Random();
int jk;
string option;
if (Age >= 16)
{
Console.WriteLine("Do you want to hear a joke?");
option = Console.ReadLine();
while (option == "yes")
{
jk = rnd.Next(lower, upper + 1);
Console.WriteLine(jokes[jk]);
Console.Read();
Console.WriteLine("Do you want to hear a joke?");
option = Console.ReadLine();
}
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);
}
我建议关注用户的答案,你可能会做这样的事情
do
{
Console.WriteLine("Do you want to hear a joke?");
option = Console.ReadLine();
}
while((option.ToLower() != "yes") || (option.ToLower() != "no") )