当用户输入不是整数的字符串时处理异常 [英] Handle Exception When User Enters a String That is Not an Integer

查看:60
本文介绍了当用户输入不是整数的字符串时处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何处理当您要求用户输入整数时发生的异常,但是他们输入的字符串不是有效整数?

解决方案

你好



最简单的解决方案是尝试将字符串转换为整数,如果有效则如果不是则为整数,它不是......



 Console.WriteLine(  plz输入一个字符串); 
string s = Console.ReadLine();

int 结果;
if int .TryParse(s, out 结果))
{
Console.WriteLine( 您已输入号码: + s);
}
else
{
Console.WriteLine(s + 不是数字);
}







Valery。


你可以使用正则表达式检查输入的字符串文字是否为数字或包含任何字符串。



样本:

  string  s =  这是字符串 ; 

string s2 = 10\" ;
string s3 = 10s;

正则表达式regex = 正则表达式( @ ^ \d +

);
bool check = regex.IsMatch(s); // false
check = regex.IsMatch(s2); // true
check = regex.IsMatch(s3); // false





检查IsMatch的返回值并提示用户输入错误。


How do we handle an exception that occurs when you ask the user to enter an integer, but they instead enter a string which is not a valid integer?

解决方案

Hello

The simplest solution is to try to convert the string to an integer, if it works it is an integer if it does not, it is not...

Console.WriteLine("plz enter a string");
string s = Console.ReadLine();

int result;
if (int.TryParse(s, out result))
{
    Console.WriteLine("you have entered the number: " + s);
}
else
{
    Console.WriteLine(s + " is not a number");
}




Valery.


You can use the regular expression to check whether the entered string literals is a number or contains any string.

sample:

string s = "This is string";

string s2 = "10";
string s3 = "10s";

Regex regex = new Regex(@"^\d+


"); bool check = regex.IsMatch(s); // false check = regex.IsMatch(s2); // true check = regex.IsMatch(s3); //false



check the return value of IsMatch and prompt the user with error.


这篇关于当用户输入不是整数的字符串时处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆