C# 如果条件不成立,做点什么

C# 如果条件不成立,做点什么,c#,C#,我的代码: string[] code = new string[9]; int[] intCode = new int[9]; int cd = 0, dvd = 0, video = 0, book = 0; for (int i = 0; i < 10; i++) { Console.Write("Enter code#{0}: ",i+1); code[i] = Console.ReadLine(); if (code[i].Length==5)

我的代码:

string[] code = new string[9];
int[] intCode = new int[9];

int cd = 0, dvd = 0, video = 0, book = 0;
for (int i = 0; i < 10; i++)
{

    Console.Write("Enter code#{0}: ",i+1);
    code[i] = Console.ReadLine();
    if (code[i].Length==5)
    {
        intCode[i] = Convert.ToInt32(code[i]);
        intCode[i] /= 100000;
        if (intCode[i] == 1)
        {
            cd++;
            break;

        }
        if (intCode[i] == 2)
        {
            dvd++;
            break;
        }
        if (intCode[i] == 3)
        {
            video++;
            break;
        }
        if (intCode[i] == 4)
        {
            book++;
            break;
        }
    }
    else
    {
        Console.WriteLine("INVALID CODE");

    }

}

基本上,我想做的是{do some thing here}要求用户重新输入数字,而不是转到for循环和i校正i并要求用户输入新的输入。

使用while和switch的组合:

        string[] code = new string[9];
        int[] intCode = new int[9];
        int cd = 0, dvd = 0, video = 0, book = 0;
        for (int i = 0; i < 10; i++)
        {
            bool isCorrectInput = false;
            while (!isCorrectInput)
            {
                isCorrectInput = true;
                Console.Write("Enter code#{0}: ", i+1);
                code[i] = Console.ReadLine();
                if (code[i].Length == 1)
                {
                    intCode[i] = Convert.ToInt32(code[i]);
                    // intCode  /= 100000;
                    switch (intCode[i])
                    {
                        case 1:
                            cd++;
                            break;
                        case 2:
                            dvd++;
                            break;
                        case 3:
                            video++;
                            break;
                        case 4:
                            book++;
                            break;
                        default:
                            isCorrectInput = false;
                            break;
                    }
                }
                else
                    isCorrectInput = false;
                if (!isCorrectInput)
                    Console.WriteLine("INVALID CODE ENTERED!");
            }
        }
编辑: 现在应该是您想要的了,还更正了else块中的错误

else
{
    Console.WriteLine("INVALID CODE");
    i -= 1;
}

你听说过情况不对吗?看起来代码中存在逻辑故障。多想想,作为一个人,你会如何解决这个问题,试着把它写下来,向一个不知道的人或一段时间内不知道的人解释?很难说你在找什么…你把一个5位数除以一个6位数,结果是1,2,3或4。如果我是你,我只会检查代码[I][0]='1'等。除以6位数是个错误,我是个新手:不是天才:@DanialAhmed每天都发生在我身上:P不工作。它说输入无效,即使输入有效。你想让用户重新输入数字,问题是,你的输入无效,因为你要检查长度是否等于5,然后除以100000,如果除以100000并解析为int,每个5位数的值将为0,你的场景中没有处理0,所以不可能更正。我猜你只是想让用户重新输入它,所以只要再做一次i,就好了。好的调整,将有助于操作