C# 如何将控制台输入验证为整数?
我已经写了我的代码,我想以这样一种方式验证它,它只允许输入整数,而不允许输入字母。这是密码,请我爱你帮我。谢谢C# 如何将控制台输入验证为整数?,c#,validation,console,C#,Validation,Console,我已经写了我的代码,我想以这样一种方式验证它,它只允许输入整数,而不允许输入字母。这是密码,请我爱你帮我。谢谢 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace minimum { class Program { static void Main(string[] args) { i
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace minimum
{
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
if (a < b)
{
if (a < c)
{
Console.WriteLine(a + "is the minimum number");
}
}
if (b < a)
{
if (b < c)
{
Console.WriteLine(b + "is the minimum number");
}
}
if (c < a)
{
if (c < b)
{
Console.WriteLine(c + "is the minimum number");
}
}
Console.ReadLine();
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
命名空间最小值
{
班级计划
{
静态void Main(字符串[]参数)
{
int a=Convert.ToInt32(Console.ReadLine());
intb=Convert.ToInt32(Console.ReadLine());
int c=Convert.ToInt32(Console.ReadLine());
if(a
您应该测试它是否为int,而不是立即进行转换。
尝试以下方法:
string line = Console.ReadLine();
int value;
if (int.TryParse(line, out value))
{
// this is an int
// do you minimum number check here
}
else
{
// this is not an int
}
只需调用Readline()并使用Int.TryParse循环,直到用户输入一个有效数字:)
希望这有助于不要立即转换用户的输入。将其放入字符串中,并使用Int32.TryParse(…)确定是否输入了数字。像这样:
int i;
string input = Console.ReadLine();
if(Int32.TryParse(input, out i))
{
// it is a number and it is stored in i
}
else
{
// it is not a number
}
注意
if (a < b) {
if (a < c) {
if(a
相当于
if (a < b && a < c) {
if(a
而且后一种形式引入的嵌套更少,可读性更高,尤其是在代码变得更复杂的情况下。此外,您可能应该永远不要使用
Convert.ToInt32
-它有一个特别糟糕和令人惊讶的角落;而且它的类型安全性也不如int.Parse
,后者更好在可能的情况下选择-或者在不确定字符串是否有效时选择int.TryParse
。基本上,尽可能避免Convert….
。我的首选解决方案是:
static void Main()
{
Console.WriteLine(
(
from line in Generate(()=>Console.ReadLine()).Take(3)
let val = ParseAsInt(line)
where val.HasValue
select val.Value
).Min()
);
}
static IEnumerable<T> Generate<T>(Func<T> generator) {
while(true) yield return generator();
}
static int? ParseAsInt(string str) {
int retval;
return int.TryParse(str,out retval) ? retval : default(int?);
}
static void Main()
{
控制台写入线(
(
从Generate(()=>Console.ReadLine())中的第行开始。获取(3)
设val=ParseAsInt(行)
其中val.HasValue
选择值
).Min()
);
}
静态IEnumerable Generate(Func生成器){
而(true)收益率返回生成器();
}
静态int?ParseAsInt(字符串str){
内部检索;
返回int.TryParse(str,out retval)?retval:默认值(int;
}
当然,根据规范(是否重试无效数字?)的不同,可能需要对其进行调整。要让控制台过滤出字母顺序的击键,您必须接管输入解析。console.ReadKey()方法是这方面的基础,它允许您嗅探按下的键。以下是一个示例实现:
static string ReadNumber() {
var buf = new StringBuilder();
for (; ; ) {
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0) {
return buf.ToString() ;
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
buf.Remove(buf.Length-1, 1);
Console.Write("\b \b");
}
else if ("0123456789.-".Contains(key.KeyChar)) {
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else {
Console.Beep();
}
}
}
例如,您可以在检测Enter键的if()语句中添加Decimal.TryParse(),以验证输入的字符串是否仍然是有效数字。这样您就可以拒绝像“1-2”这样的输入。Double/Float: 我只是扩展了@Hans Passant的答案(注意小数点分隔符和“-”号): 试试这个简单的
try
{
string x= "aaa";
Convert.ToInt16(x);
//if success is integer not go to catch
}
catch
{
//if not integer
return;
}
哇,这是一个同时抛出所有这些解决方案的记录吗?我们应该删除它们吗?代码?一个谜题?嗯,这不好:-)-我打算让功能组合起来,避免使用大型功能-我想生成函数需要一点时间来适应…+1,但您可能应该验证修饰符:-)(Ctrl,Alt…)没错。我们称之为功能:)
static double ReadNumber()
{
var buf = new StringBuilder();
for (; ; )
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0)
{
Console.WriteLine();
return Convert.ToDouble(buf.ToString());
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0)
{
buf.Remove(buf.Length - 1, 1);
Console.Write("\b \b");
}
else if (System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.Contains(key.KeyChar) && buf.ToString().IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) == -1)
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("-".Contains(key.KeyChar) && buf.ToString().IndexOf("-") == -1 && buf.ToString() == "")
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("0123456789".Contains(key.KeyChar))
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else
{
Console.Beep();
}
}
}
try
{
string x= "aaa";
Convert.ToInt16(x);
//if success is integer not go to catch
}
catch
{
//if not integer
return;
}
string Temp;
int tempInt,a;
bool result=false;
while ( result == false )
{
Console.Write ("\n Enter A Number : ");
Temp = Console.ReadLine ();
result = int.TryParse (Temp, out tempInt);
if ( result == false )
{
Console.Write ("\n Please Enter Numbers Only.");
}
else
{
a=tempInt;
break;
}
}
var getInput=Console.ReadLine();
int option;
//validating input
while(!int.TryParse(getInput, out option))
{
Console.WriteLine("Incorrect input type. Please try again");
getInput=Console.ReadLine();
}