首页 > 解决方案 > 如何防止在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();
    }
}
}

标签: c#

解决方案


正如评论中所建议的,我会使用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"...

推荐阅读