Как я могу сделать это, чтобы моя программа не вылетела из строя, когда я ввожу символ вместо int

и это одна из моих первых «почти работающих программ», дело в том, что когда я набираю символ вместо 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();
                }
            }
        }
    }
}

person tactoc    schedule 08.08.2018    source источник
comment
Если его пользовательский ввод вызывает проблему, добавьте проверку на экран ввода, чтобы принудительно использовать int еще до того, как он дойдет до этого кода.   -  person Brad    schedule 08.08.2018
comment
int answer = Convert.ToInt32(Console.ReadLine()); ‹--- вот где твоя проблема. выполните некоторые проверки значения перед преобразованием в int, чтобы убедиться, что это действительно число, иначе запросите пользователя и сообщите ему, что они ввели данные мусора. Также для вашего собственного здравомыслия вы можете очистить пустые строки между фигурными скобками в нижней части кода ... лично меня это свело бы с ума.   -  person user2366842    schedule 08.08.2018
comment
Вы также можете заменить if(answer != num1 + num2) на else (это не проблема, но все же стоит понимать)   -  person Rafalon    schedule 08.08.2018


Ответы (2)


Самый простой способ - это что-то вроде

int answer;
while (!int.TryParse(Console.ReadLine(), out answer))
{
    Console.Write("You didn't provide a number, please try again:");
}
person Evertude    schedule 08.08.2018
comment
Это сработало. Спасибо - person tactoc; 08.08.2018

Изменить: решение Evertude гораздо лаконичнее.

Вы можете использовать try catch и попробовать преобразовать ввод в целое число.

int answer = 0;
while(answer == 0)
{
    try
    {
        var inputAnswer = Convert.ToInt32(Console.ReadLine());
        answer = inputAnswer;
    }catch
    {
        Console.WriteLine("Please enter a valid number.");
    }
}
person tstephansen    schedule 08.08.2018
comment
Это тоже работает - person tactoc; 08.08.2018
comment
Хотя это, вероятно, не имеет большого значения для такого простого приложения, следует отметить, что использование этого маршрута потенциально может значительно снизить производительность. Всегда лучше проверять подобные вещи, чем допускать, чтобы это провалилось оператором catch, если вы можете этого избежать. - person user2366842; 10.08.2018