编译错误- c# -如何处理空用户输入

本文关键字:处理 用户 输入 错误 何处理 编译 | 更新日期: 2023-09-27 17:53:21

大家好,我仍然是一个编程初学者。所以我的问题是如何处理空用户输入在我的简单代码?每次我按回车键时,它都会给我一个错误,没有一个值。我的代码:

    //Program to find the number is even or odd.
using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practice
   {
     class test
     {
       static void Main (String[] args)
        {
          int i;
            Console.Write (" Enter a number: ");
            i = int.parse (Console.ReadLine()); // Where the error occurs when there is no user input.
             if(i % 2 ==0)
              {
                Console.Write (" The number is even");
                Console.Read();
              }
               else
                {
                 Console.Write (" The number is odd");
                 Console.Read();
                }
              }
            }
          }

任何想法?谢谢。

编译错误- c# -如何处理空用户输入

尝试如下内容

string line = Console.ReadLine();
if(!string.IsNullOrEmpty(line)){
 //Non empty input
}else{
 //Handle here
}

您有两个选择:

  1. 使用TryParse代替Parse。这样就不会抛出异常,你可以测试该值是否有效,如果无效则再次询问。

  2. 将代码包装在try catch块中,以优雅地处理异常,并要求用户再试一次

在第一种情况下,您将以如下方式结束:

static void Main (String[] args)
{
    int i;
    Console.Write (" Enter a number: ");
    bool result = int.TryParse(Console.ReadLine(), out i);
    if (result)
    {
        // your normal code
    }
    else
    {
        Console.WriteLine("That wasn't a number.");
    }
}

在第二种情况下,它类似于:

static void Main (String[] args)
{
    int i;
    try
    {
        Console.Write (" Enter a number: ");
        i = int.parse (Console.ReadLine());
    }
    catch (Exception)
    {
        Console.WriteLine("That wasn't a number.");
        return;
    }
    // rest of your code
}

您可以使用String检查空用户输入。IsNullOrWhiteSpace方法。这个方法检查任何输入中的空格或null。

你可以这样检查你的输入:

if (string.IsNullOrWhiteSpace(line))
{
   ...//parse
}

由于解析的是整数,因此可能需要使用Int32。函数解析数据。它将返回一个布尔值,指示输入是否被成功解析。

int i =0;
if (Int32.TryParse(Console.ReadLine(), out i))
{
  ...//continue
}
    static void Main(string[] args)
    {
        int i;
        Console.Write(" Enter a number: ");
        if (Int32.TryParse(Console.ReadLine(), out i))
        {
            if (i % 2 == 0)
            {
                Console.Write(" The number is even");
            }
            else
            {
                Console.Write(" The number is odd");
            }
        }
        else
        {
            Console.Write(" You have to enter a number I can parse into an integer, dummy!");
        }
    }