c# - 如何防止在C#中输入null enter
问题描述
我刚刚开始了一个餐桌计划。我只是从互联网上学习 C# 的实习生,所以我在这方面不太擅长。
我只是想让程序根据用户运行。我希望如果用户简单地按回车,程序不应该崩溃。那就是我只想知道如何防止空输入。这是使用的代码:
if 用于写一行的“______”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tables
{
class Program
{
static void Main(string[] args)
{
goto found;
found:
Console.WriteLine("");
string textToEnter = "MULTIPLATION TABLES";
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
Console.WriteLine("");
Console.WriteLine("________________________________________________________________________________");
Console.WriteLine("");
int num, j, i;
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32( Console.ReadLine());
while (num == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32(Console.ReadLine());
}
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
while (j == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
}
i = Convert.ToInt32(j);
for (j=1; ; j++)
{
if (j > i)
{
break;
}
Console.WriteLine(num + " * " + j + " = " + num * j);
}
string str;
Console.Write("do you want to continue? (y/n) :- " );
str= Console.ReadLine();
foreach (char ch in str)
{
if (ch == 'y')
{
goto found;
}
else if (ch=='n' )
{
Console.WriteLine("");
Console.WriteLine("THANK YOU FOR USING MY PRODUCT");
}
else
{
Console.WriteLine("please enter a valid input");
}
}
Console.ReadKey();
}
}
}
解决方案
正如评论中所建议的,我会使用int.TryParse(),但在do...while()循环内。使用单独的标志(布尔值)来跟踪用户是否应该继续重试:
bool invalid;
int num, j, i;
do
{
invalid = true;
Console.Write("enter the number of which table u need ? :- ");
String response = Console.ReadLine();
if (int.TryParse(response, out num))
{
invalid = false;
}
else
{
Console.WriteLine("Invalid input. Please try again.");
}
} while (invalid);
// ...repeat the above do...while() block for "j" and "i"...
推荐阅读
- android - 可搜索微调器(toptoche)从 mysql 加载数据
- javascript - jsPDF-AutoTable:特定行的字体样式“斜体”
- c# - 设置 ironpython:找不到模块
- android - 当我输入相同的用户名时,它给了我“错误的输入”?
- r - PCoA 函数 pcoa 提取向量;解释的方差百分比
- authentication - SignalR 核心 JWT 声明
- timestamp - 删除 db2 时间戳微秒
- matlab - 在 MATLAB 上使用 zsh 通过别名运行命令行
- ionic-framework - 离子后退按钮不会动态更改文本
- apache-kafka - 我们可以在 Kafka 中有多少个分区?