【发布时间】:2018-08-08 12:59:28
【问题描述】:
这是我的第一个“几乎可以工作的程序”之一,问题是当我输入一个字符而不是一个 int 时,我的应用程序会立即崩溃。而且我知道我必须使用 tryparse 或类似的东西做一些事情,我只是目前不确定我应该如何将它放入我的代码中,因为它是一个循环。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace threeTries
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Title = "3 Tries";
Console.WriteLine("3 Tries\n-------");
System.Threading.Thread.Sleep(1000);
Console.ForegroundColor = ConsoleColor.White;
System.Threading.Thread.Sleep(2000);
Console.Clear();
Console.WriteLine("You have to score the highest score possible\nYou have to answer simple math questions\n ");
Console.Clear();
var score = 0;
var tries = 0;
bool highscore = false;
var numberHighscore = 0;
while (true)
{
Random rngNumber = new Random();
var num1 = rngNumber.Next(1, 100);
var num2 = rngNumber.Next(1, 100);
Console.ForegroundColor = ConsoleColor.Yellow;
if (highscore == true)
{
Console.WriteLine("Your highscore is {0}", numberHighscore);
}
Console.WriteLine("{0} Score || Tries {1}/3", score, tries);
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("What is {0} + {1} ?", num1, num2);
Console.Write("Answer : ");
int answer = Convert.ToInt32(Console.ReadLine());
if (answer == num1 + num2)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your answer was correct");
score++;
System.Threading.Thread.Sleep(1000);
Console.Clear();
}
if (answer != num1 + num2)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Your answer is wrong");
tries++;
System.Threading.Thread.Sleep(1000);
Console.Clear();
}
if (tries > 3) {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Game Over");
System.Threading.Thread.Sleep(1000);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Your final score was {0}", score);
numberHighscore = score;
System.Threading.Thread.Sleep(5000);
highscore = true;
score = 0;
tries = 0;
Console.Clear();
}
}
}
}
}
【问题讨论】:
-
如果它的用户输入导致问题,在输入屏幕上添加验证以强制一个 int 在它到达此代码之前。
-
int answer = Convert.ToInt32(Console.ReadLine()); -
您也可以将
if(answer != num1 + num2)替换为else(不是问题,但仍然值得理解)
标签: c# while-loop tryparse