【发布时间】:2021-03-12 15:07:57
【问题描述】:
我目前正在做一个基本的 RNG 程序,但在消毒时遇到了麻烦。我在编程方面很糟糕,所以我可能会遗漏一些东西,但我不知道如何确保用户没有输入字符串。我的问题出在代码底部的最后一个 if 语句中。任何帮助将不胜感激!代码如下:
using System;
namespace Lab_9
{
class Program
{
static void Main(string[] args)
{
//Declaring range for RNG
int minValue = 1;
int maxValue = 10;
//Creating RNG
Random random = new Random();
int number = random.Next(minValue, maxValue);
//Getting user int
Console.WriteLine("Please guess a number between 1-10");
int UserInput = Convert.ToInt32(Console.ReadLine());
bool validInput = Sanitize(UserInput);
//Checking if their number is greater than the RNG Number
if (UserInput > number)
{
Console.WriteLine("Your number is more than the generated number");
}
//Checking if it is smaller
if (UserInput < number)
{
Console.WriteLine("Your number is less than the generated number");
}
//Checking if they guessed the right number
if (UserInput == number)
{
Console.WriteLine("Congrats! You guessed the number!");
}
Console.WriteLine("The random number was " + number);
}
//Sanitizing their input
private static bool Sanitize(int UserInput)
{
//Checks for invalid numbers
if(UserInput > 10)
{
Console.WriteLine("Please do not enter a number that is greater than 10");
return false;
}
if(UserInput < 1)
{
Console.WriteLine("Please do not enter a number that is less than 1");
return false;
}
//Checking if they put chars instead of numbers
if()
{
Console.WriteLine("Please do not enter a letter, only a number");
return false;
}
return true;
}
}
}
【问题讨论】:
-
查看Int.TryParse 作为您当前拥有的方式,如果用户输入的不是数字,它会抛出。 TBH,我会在
Sanitize例程中进行此检查并完成它。 -
感谢您的帮助!
-
不客气,如果您对此仍有疑问,请更新您的帖子,有人会很乐意为您提供帮助。
标签: c# sanitization