如果用户输入“退出”或“退出”,我无法循环我的程序,使其跳出循环。当用户输入退出或退出时打破循环c#
当我键入任何字符串时,我的程序崩溃,因为它试图分析字符串输入到一个int。有什么建议?
namespace DiceRolling
{
/* We’re going to write a program that makes life easier for the player of a game like this. Start the
program off by asking the player to type in a number of dice to roll.Create a new Random
object and roll that number of dice.Add the total up and print the result to the user. (You should
only need one Random object for this.) For bonus points, put the whole program in a loop and allow them to keep typing in numbers
until they type “quit” or “exit”. */
class DiceRolling
{
static void RollDice(int numTries)
{
Random random = new Random();
//Console.Write("Please enter the number of dice you want to roll: ");
//int numTries = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int dieRoll;
for (int i = 1; i <= numTries; i++)
{
dieRoll = random.Next(6) + 1;
Console.WriteLine(dieRoll);
sum += dieRoll;
}
Console.WriteLine("The sum of your rolls equals: " + sum);
}
static void Main(string[] args)
{
while (true)
{
Console.Write("Please enter the number of dice you want to roll: ");
string input = Console.ReadLine();
int numTries = Convert.ToInt32(input);
//bool isValid = int.TryParse(input, out numTries);
RollDice(numTries);
Console.ReadKey();
if (input == "quit" || input == "exit")
break;
}
}
}
}
当解析'“quit”'为int时,会发生什么你期望发生?也许你想要某种菜单,用户输入一个数字,而不是“退出”?例如。 '0'还是'-1'? – HimBromBeere
只需在变量输入的readline之后移动检查以退出或立即退出。 – Steve
这也是一件小事,但正确的英文术语将是“骰子”而不是“骰子”。 –