如何设置无输入的异常处理

时间:2015-09-21 02:30:38

标签: c#

这是我的程序,用于接收2个数字和一个操作员,然后进行数学计算并吐出答案(感谢他之前的异步帮助)。到目前为止,一切都很好,除非我什么也没输入。我试图让它说没有输入,再试一次,但它只是崩溃了。有谁知道为什么?提前谢谢。

using System;
class Calculation
{
    public static void Main(string[] data)
    {

        if (data.Length == 0)
        {
            Console.WriteLine("No input... Try again");

            return;
        }

        double result;

        if (!Double.TryParse(data[0], out result))
        {
            Console.WriteLine("Invalid input: " + data[0]);

            return;
        }

        Console.WriteLine("Starting with number: " + result);

        char op;
        double number;

        string errorMessage;

        do
        {
            if (!TryGetData(out op, out number, out errorMessage))
            {
                Console.WriteLine("Invalid input: " + errorMessage);

                continue;
            }

            switch (op)
            {
                case '+':
                    result += number;
                    break;
                case '-':
                    result -= number;
                    break;
                case '*':
                    result *= number;
                    break;
                case '/':
                    result /= number;
                    break;
                default:
                    Console.WriteLine("Done");
                    continue;
            }

            Console.WriteLine("Result = " + result.ToString());


        } while (Char.ToLower(op) != 'q');
    }

    static bool TryGetData(out char anOperator, out double aNumber, out string message)
    {
        aNumber = 0;
        message = null;

        Console.Write("Enter an operator and a number or 'q' to quit: ");

        var line = Console.ReadLine();

        anOperator = line[0];

        if (anOperator != 'q' && anOperator != 'Q')
        {
            if (line.Length <= 2)
            {
                message = "Enter an operator followed by a space and then a number.";

                return false;
            }

            var isValidNumber = Double.TryParse(line.Substring(2), out aNumber);

            if (!isValidNumber)
            {
                message = "Invalid input: " + line.Substring(2);

                return false;
            }

            if (isValidNumber && (anOperator == '/' && aNumber == 0))
            {
                message = "Cannot divide by 0.";

                return false;
            }

            if (line[1] != ' ')
            {
                message = "Make sure to put a space between operator and number.";

                return false;
            }

        }

        return true;
    }
}

1 个答案:

答案 0 :(得分:0)

您告诉它检查变量null的length属性。 如果要删除,可以检查是否为null,然后检查长度。

C#本质上是一种短路语言,如果if语句的第一部分为假(或为真),则其他部分不会被评估。

if (data == null || data.length == 0) 
{
    Console.WriteLine("No input... Try again");
    return;
}