C#控制台应用程序在结束时卡住了想重新输入n如果正确则继续前进 [英] C# console app stuck at end of while would like to reenter input n move on if correct

查看:222
本文介绍了C#控制台应用程序在结束时卡住了想重新输入n如果正确则继续前进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我在控制台应用程序中有一个循环。我正在使用while循环并抓取用户输入。我正在检查输入,如果输入无效,我想进入开头,这样他们就可以再试一次。目前一旦他们出错了我最终会陷入困境,如果他们再次输入正确的输入我就会卡在最后



Hello all I have a loop in a console application. I am using a while loop and grabbing the users input. I am checking the input and if the input isn’t valid I would like to go to the beginning so they can try again. Currently once they are wrong I am stuck at the end it doesn’t matter if they enter the right input again im stuck at the end

for(int i = 0; i < answers.Length; i++)
            {
                Console.WriteLine("Question " + (i + 1) + ": ");
                string input = Console.ReadLine();
                
                if(char.TryParse(input, out char inserted))
                {
                    answers[i] = inserted;

                    // Validate the answer.
                    while (!Valid(answers[i]))
                    {
                        Console.WriteLine("ERROR: Valid answers are A, B, C, or D.");
                        Console.Write("Question " + (i + 1) + ": ");
                        input = Console.ReadLine();
                        if(char.TryParse(input, out char userChar))
                        {
                            answers[i] = inserted;
                        }
                    }
                }
            }





我尝试了什么:





What I have tried:

Moving stuff around and trying to exit the loop but stuck at the end

推荐答案

您的以下情况似乎是罪魁祸首。您正在使用插入变量,同时输入并将其放入 userChar



在这两个地方使用插入或在条件下更改。请尝试以下方法:



Your following condition seems to be culprit. You are using inserted variable while you are taking input and putting it in userChar.

Either use inserted at both places or change your while condition. Try the following:

if(char.TryParse(input, out char userChar))
{
     answers[i] = userChar; // note this 
}





或者您需要在 TryParse 方法调用中使用插入





or you need to use inserted in your TryParse method call:

if(char.TryParse(input, out char inserted))
{
     answers[i] = inserted;
}


这篇关于C#控制台应用程序在结束时卡住了想重新输入n如果正确则继续前进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆