【发布时间】:2020-01-26 03:57:40
【问题描述】:
我现在只有两节课。我正在努力让程序在输入 QUIT 时退出。
此功能有效,但(我相信)while 循环在退出应用程序之前多运行一次Utility.GetCommand()。
当键入 QUIT 时,控制台输出“请输入您的命令:”,然后系统生成退出消息。我不知道这是为什么。
这里是主页。
using System;
namespace Application
{
class Program
{
static void Main(string[] args)
{
//Fields
bool welcome = false;
while (Utility.Quit == false)
{
if (welcome == false)
{
Console.WriteLine("Welcome to CSF Scheduler. Please enter a command to get started.");
Console.WriteLine("Type 'HELP' for a list of commands.");
welcome = true;
}
Utility.GetCommand(Console.ReadLine());
Utility.HandleCommand(Utility.Command);
}
}
}
}
这里是实用程序类
using System;
public abstract class Utility
{
public Utility()
{
}
//Fields
public static string Command { get; private set; }
public static bool Quit { get; private set; }
//Methods
public static void GetCommand(string command)
{
Console.Write("Please enter your command: ");
Command = command;
}
public static void HandleCommand(string command)
{
switch (Command)
{
case "QUIT":
Quit = true;
break;
default:
Console.WriteLine("Command not recognized. Please type 'HELP' to see a list of commands.");
break;
}
}
}
【问题讨论】:
-
在执行
Console.Write("Please enter your command: ")之前,您正在执行Console.ReadLine而不是将string传递给GetCommand,只需执行Command = Console.ReadLine();即可
标签: c# loops while-loop