如果用户输入无效,如何重复提问? C# [英] How to repeat question if user input is invalid? C#

查看:66
本文介绍了如果用户输入无效,如何重复提问? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简而言之,我正在进行一个测验,其中包含5个问题,每个问题有三个选项(a,b,c)。如果用户输入的不是这三个字符,我希望问题循环回来。输入a,b或c后,我希望出现下一个问题。如果答案是正确的,用户
也会获得一分。这就是我到目前为止:

In short, I'm making a quiz with 5 questions each with three options (a,b,c). If the user inputs something other than those three characters, I want the question to loop back. Once a, b, or c is inputted, then I want the next question to appear. The user also earns one point if answer is correct. This is what I have so far:

Console.WriteLine("Question 1: When was Nintendo's first home console released?");
            Console.WriteLine("a: 1985");
            Console.WriteLine("b: 1991");
            Console.WriteLine("c: 1973");
            Console.Write("Enter a, b or c: ");

            answerOption = Convert.ToChar(Console.ReadLine());

                switch (answerOption)
                {
                    case 'a': total = total + 1; break;
                    case 'b': total = total + 0; break;
                    case 'c': total = total + 0; break;            
                }
                Console.WriteLine("Invalid answer. Please enter a, b or c.");
                answerOption = Convert.ToChar(Console.ReadLine());
            

            Console.WriteLine("Question 2: GameBoy is one of the most common


之一我知道我需要在切换之前进行某种循环,但我不知道它应该是while还是while。一旦输入a,b或c,我该如何退出循环?

I know I need some kind of loop before the switch, but I don't know whether it should be while or do while. And how do I get out of the loop once a, b, or c is inputted?

推荐答案

试试这个:

do
{
	Console.WriteLine( "Question 1: When was Nintendo's first home console released?" );
	Console.WriteLine( "a: 1985" );
	Console.WriteLine( "b: 1991" );
	Console.WriteLine( "c: 1973" );
	Console.Write( "Enter a, b or c: " );

	answerOption = Convert.ToChar( Console.ReadLine() );

	switch( answerOption )
	{
	case 'a': total = total + 1; break;
	case 'b': total = total + 0; break;
	case 'c': total = total + 0; break;
	default:
		Console.WriteLine( "Invalid answer. Please enter a, b or c." );
		answerOption = '\0'; break;
	}
} while( answerOption == '\0' );





这篇关于如果用户输入无效,如何重复提问? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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