如何检查字符串数组的偶数位置是否只有数字?

How do I check that even positions of a string array have only numbers?

我正在学习我的第一门编程语言——C#。

我正在做学徒期间的第一个项目,教我 C#。就是制作一个基本的计算器。

基本计算器接受字符串输入并提供结果。例如,输入:“5 + 5”。答案将是十进制格式的 10。

然而,我的部分验证是让字符串数组的偶数索引只能是数字,而字符串数组的奇数索引只能是“+”、“-”、“*”、“的运算符/”。我该怎么做?

我试过在这里做,但我很挣扎:

for (int index = 0; index <= calculatorInput.Length; index++)
{
    if (index % 2 == 0)
    {
        if (Decimal.TryParse(calculatorInput[index]))
        {
            throw new CalculatorException("Even indexes must contain a number");
        }
        //check for number
    }
    else if (//code here)
    {
        throw new CalculatorException("Odd indexes must contain an operator");
        //check for operator
    }
}

抱歉,如果这个问题太简单了,但我将不胜感激!

您可以专注于运营商进行验证。它们必须始终位于输入字符串内的某个位置。如果您的计算器接受负数,减号运算符是一个例外。但是如果计算器是基本的并且不支持负数,那么下面的代码应该足以进行运算符验证:

string inputString = "10 + 10";

int index = inputString.IndexOf('+');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

index = inputString.IndexOf('*');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

index = inputString.IndexOf('/');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

index = inputString.IndexOf('-');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
    throw new CalculatorException("YOUR ERROR MESSAGE");

///Calculation code

为了提高可读性,我没有创建嵌套的 if-else 语句。 在这个代码块之后,您可以放置​​您的计算代码。我觉得对于新手来说已经足够了。

对于迟到的回复,我深表歉意。 Rufus L (https://whosebug.com/users/2052655/rufus-l) 的评论帮助提供了我当时需要的解决方案。

decimal temp; if (decimal.TryParse(calculatorInput[index].ToString(), out temp)){} The TryParse method takes a string and an out parameter, which you are missing. But there are better ways to do what you want. – Rufus L Nov 1 '19 at 18:58

然而,所有的回答和评论对我的发展都非常有帮助。计算器现已完成,但仍有改进的余地。