c# 使用什么循环

标签 c# loops

好的,我的问题是这样的,目前我有 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:要退出程序(请参阅评论中的附加问题),只需从 Mainreturn:

 ...
 if (answer1 == "NO") {
   Console.WriteLine("Your loss"); 

   return; // return from Main will exit the program
 }

关于c# 使用什么循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41623450/

相关文章:

c# - 多个集线器的 SignalR 分离事件

c# - 在 int 和 string 中装箱和拆箱

c# - 将 ListView 中的值列表显示到电子邮件正文中

javascript - JavaScript 中的循环

ios - 在一个紧密的循环中读取或写入 NSUserDefaults 是不是很糟糕?

java - 如何将字符串的字符与数组的索引相匹配

c# - 目标框架中缺少“WindowsBase”、 'PresentationCore'、 'PresentationFramework'

c# - 如何在控制标签内包含条件语句?

jquery - 如何动态退出jquery $.each()?

数据帧上的游程长度编码