C# How to loop user input until the datatype of the input is correct?(C#如何循环用户输入,直到输入的数据类型正确?)
问题描述
如何使这段代码循环要求用户输入直到 int.TryParse()
How to make this piece of code loop asking for input from the user until int.TryParse()
成功了吗?
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
System.Console.WriteLine("You must enter an integer type value"); 'need to make it ask user for another input if first one was of invalid type'
}
有用答案后的代码版本:
Version of the code after the helpful answer:
//setX
public void setX()
{
//take the input from the user
string temp;
int temp2;
System.Console.WriteLine("Enter a value for X:");
temp = System.Console.ReadLine();
if (int.TryParse(temp, out temp2))
x = temp2;
else
{
Console.WriteLine("The value must be of integer type");
while (!int.TryParse(Console.ReadLine(), out temp2))
Console.WriteLine("The value must be of integer type");
x = temp2;
}
}
推荐答案
while (!int.TryParse(Console.ReadLine(), out mynum))
Console.WriteLine("Try again");
public void setX() {
Console.Write("Enter a value for X (int): ");
while (!int.TryParse(Console.ReadLine(), out x))
Console.Write("The value must be of integer type, try again: ");
}
试试这个.我个人更喜欢使用 while
,但 do .. while
也是有效的解决方案.问题是我真的不想在任何输入之前打印错误消息.然而 while
也有更复杂的输入问题,不能被压入一行.这真的取决于你到底需要什么.在某些情况下,我什至建议使用 goto
,即使有些人可能会因此而追踪我并用鱼打我.
Try this. I personally prefer to use while
, but do .. while
is also valid solution. The thing is that I don't really want to print error message before any input. However while
has also problem with more complicated input that can't be pushed into one line. It really depends on what exactly you need. In some cases I'd even recommend to use goto
even tho some people would probably track me down and slap me with a fish because of it.
这篇关于C#如何循环用户输入,直到输入的数据类型正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C#如何循环用户输入,直到输入的数据类型正确?


基础教程推荐
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01