gpt4 book ai didi

c# - 如何让控制台应用程序运行直到用户输入 "Q"、 "q"、 "Quit"或 "quit"以终止它?

转载 作者:太空狗 更新时间:2023-10-30 01:27:00 26 4
gpt4 key购买 nike

如何让控制台应用程序运行直到用户输入“Q”、“q”、“Quit”或“quit”来终止它?

这是我当前的代码:

public class Class1
{
[STAThread]
static void Main(string[] args)
{
string userName;
int i = 0, totalCal = 0, cal = 1;

Console.WriteLine("Welcome to the magical calorie counter!");
Console.WriteLine();
Console.Write("Enter in your name -> ");
userName = Console.ReadLine();

for (i = 0; i <= 10; i++)
{
Console.WriteLine("Hello {0}.....Let's add some calories!!", userName);
}// end for loop

Console.WriteLine();

while (cal != 0)
{
Console.Write("Enter some Calories:<or 0 to quit>: ");

cal = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("You entered {0}", cal);
Console.WriteLine();

totalCal += cal;
Console.WriteLine();
Console.WriteLine("-------------------So far you have a total of {0}------------------", totalCal);
Console.WriteLine();
Console.WriteLine();
}// end of while
}// end of amin
}//end of class

最佳答案

假设您的程序中没有任何其他错误...只需添加几行,如下所示:

using System;

class Class1
{

[STAThread]
static void Main(string[] args)
{
string userName;
string line;
int i = 0, totalCal = 0, cal = 1;

Console.WriteLine("Welcome to the magical calorie counter!");
Console.WriteLine();
Console.Write("Enter in your name -> ");
userName = Console.ReadLine();

for (i = 0; i <= 10; i++)
{
Console.WriteLine("Hello {0}.....Let's add some calories!!", userName);
}// end for loop
Console.WriteLine();


while (true)
{

Console.Write("Enter some Calories:<or 0 to quit>: ");
line = Console.ReadLine().ToLower();
if (line == "q" || line == "quit")
{
break;
}
else if (!int.TryParse(line, cal))
{
Console.WriteLine("Not a valid option. Please try again.");
continue;
}
Console.WriteLine("You entered {0}", cal);
Console.WriteLine();

totalCal += cal;
Console.WriteLine();
Console.WriteLine("-------------------So far you have a total of {0}------------------", totalCal);
Console.WriteLine();
Console.WriteLine();
}// end of while
}// end of amin
}

关于c# - 如何让控制台应用程序运行直到用户输入 "Q"、 "q"、 "Quit"或 "quit"以终止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3732673/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com