好的,我的问题是这样的,目前我有 3 个可能的答案:是、否以及其他所有问题。我想让我的程序写“Pardon me?”直到我回答是或否...我是使用 c# 的新手并且仍在学习所以请尽可能简单。谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Pitalica
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Kvisko");
Console.WriteLine("\"Hello Traveller!!\" says a man. \"What's your name?\"");
string playerName = Console.ReadLine();
Console.WriteLine("\"Hi " + playerName + ", welcome to the beautiful city of Osijek!\nI would like to give you a tour of our little town, but I don't have time to do so right now.\nI need to go to class.\"");
Console.WriteLine("He looks at you with your backpack on your back.\"But I could show you later if you're up to?\"");
string answer1 = Console.ReadLine();
if (answer1 == "yes")
Console.WriteLine("\"We have a deal, " + playerName + "!\"");
else if (answer1 == "no")
Console.WriteLine("\"Your loss," + playerName + "...\"");
else
{
Console.WriteLine("Pardon me?");
}
Console.WriteLine("After some time...");
}
}
}
最佳答案
从技术上讲,您可以实现任何循环,但我建议使用while
...
string answer1 = Console.ReadLine();
while (answer1 != "yes" && answer1 != "no") {
Console.WriteLine("Pardon me?");
answer1 = Console.ReadLine();
}
...
当 answer1
不正确时,请继续提问。
编辑:正如 Hogan 在评论中建议的那样,我们应该对用户友好:让他/她在任何带有前导和尾随空格的寄存器中输入 YES/no :
...
// with Trim() and ToUpper() all "Yes", " yes", "YES " are OK
string answer1 = Console.ReadLine().Trim().ToUpper();
while (answer1 != "YES" && answer1 != "NO") {
Console.WriteLine("Pardon me?");
answer1 = Console.ReadLine().Trim().ToUpper();
}
...
编辑 2:要退出程序(请参阅评论中的附加问题),只需从 Main
return:
...
if (answer1 == "NO") {
Console.WriteLine("Your loss");
return; // return from Main will exit the program
}
关于c# 使用什么循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623450/