英文:
How to only accept valid options in ReadLine (C#)
问题
Program.cs
namespace DrivingLicenseExam
{
    class Program
    {
        static void Main(string[] args)
        {
            Questions firstQuestion = new Questions("1. You may drive off the paved roadway to pass another vehicle: ", "c", "");
            Console.WriteLine(firstQuestion.question);
            Console.WriteLine("----");
            Console.WriteLine("a) - If the shoulder is wide enough to accommodate your vehicle.");
            Console.WriteLine("b) - If the vehicle ahead of you is turning left.");
            Console.WriteLine("c) - Under no circumstances.");
            Console.Write("Your answer is: ");
            firstQuestion.UserAnswer = Console.ReadLine().ToLower();
            if (firstQuestion.UserAnswer == firstQuestion.correctAnswer)
            {
                totalScore++;
            }
        }
    }
}
Questions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrivingLicenseExam
{
    class Questions
    {
        public string question;
        public string correctAnswer;
        private string userAnswer;
        public Questions(string aQuestion, string aCorrectAnswer, string aUserAnswer)
        {
            question = aQuestion;
            correctAnswer = aCorrectAnswer;
            UserAnswer = aUserAnswer;
        }
        public string UserAnswer
        {  
           get { return userAnswer; } 
           set {
                    if (value == "a" || value == "b" || value == "c")
                    {
                        userAnswer = value;
                    }
                    else
                    {
                        Console.WriteLine("Invalid Answer. - Please choose from 'a', 'b' or 'c'.");
                    }
           }
        }
    }
}
The code you provided is now free of HTML entity encoding for quotation marks, and the Chinese translation has been removed, as you requested.
英文:
This Driving License Exam project would be my 4th code after starting to learn programming.
Program.cs
namespace DrivingLicenseExam
{
    class Program
    {
        static void Main(string[] args)
        {
            Questions firstQuestion = new Questions("1. You may drive off the paved roadway to pass another vehicle: ", "c", "");
            Console.WriteLine(firstQuestion.question);
            Console.WriteLine("----");
            Console.WriteLine("a) - If the shoulder is wide enough to accommodate your vehicle.");
            Console.WriteLine("b) - If the vehicle ahead of you is turning left.");
            Console.WriteLine("c) - Under no circumstances.");
            Console.Write("Your answer is: ");
            firstQuestion.UserAnswer = Console.ReadLine().ToLower();
            if (firstQuestion.UserAnswer == firstQuestion.correctAnswer)
            {
                totalScore++;
            }
        }
    }
} 
Questions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DrivingLicenseExam
{
    class Questions
    {
        public string question;
        public string correctAnswer;
        private string userAnswer;
        public Questions(string aQuestion, string aCorrectAnswer, string aUserAnswer)
        {
            question = aQuestion;
            correctAnswer = aCorrectAnswer;
            UserAnswer = aUserAnswer;
        }
        public string UserAnswer
        {  
           get { return userAnswer; } 
           set {
                    if (value == "a" || value == "b" || value == "c")
                    {
                        userAnswer = value;
                    }
                    else
                    {
                        Console.WriteLine("Invalid Answer. - Please choose from \"a\", \"b\" or \"c\".");
                    }
           }
        }
    }
}
I am using objects to create the questions with the valid answers and I want the user to only be able to enter "a", "b" or "c", otherwise it should say:
Console.WriteLine("Invalid answer.");
Console.WriteLine("Please choose between \"a\", \"b\" or \"c\".");
This is an example from a previous project but I am not sure how to integrate it in this one:
do
    {
        string measureUnit = Console.ReadLine().ToLower();
        if (measureUnit == "km" || measureUnit == "cm" || measureUnit == "m")
        {
            return measureUnit;
        }
        Console.WriteLine("Incorrect measurement");
        Console.Write("Choose: ");
                
    } while (true);
Thank you! ![]()
答案1
得分: 1
以下是您提供的内容的翻译:
"我能想到的最简单方法是创建一个验证方法和一个在问题类中验证答案的方法。
下面的主程序中的 while 循环不断调用“ValidateAnswer”方法,直到收到有效输入为止。
class Questions
{
    public string question;
    public string correctAnswer;
    private string userAnswer;
    public Questions(string aQuestion, string aCorrectAnswer)
    {
        question = aQuestion;
        correctAnswer = aCorrectAnswer;
    }
    public bool ValidateAnswer(string aUserAnswer)
    {
        if (aUserAnswer == "a" || aUserAnswer == "b" || aUserAnswer == "c")
        {
            return true;
        }
        Console.WriteLine("无效答案。");
        Console.WriteLine("请选择'a'、'b'或'c'之间的一个。");
        return false;
    }
    public bool VerifyAnswer(string aUserAnswer)
    {
        return (aUserAnswer == correctAnswer);
    }
    static void Main(string[] args)
    {
        Questions firstQuestion = new Questions("1. 您可以驶离铺设的道路以超越另一辆车:", "c");
        Console.WriteLine(firstQuestion.question);
        Console.WriteLine("----");
        Console.WriteLine("a) - 如果路肩足够宽以容纳您的车辆。");
        Console.WriteLine("b) - 如果前面的车正在左转。");
        Console.WriteLine("c) - 无论如何都不可以。");
        Console.Write("您的答案是:");
        string answer = Console.ReadLine().ToLower();
        while (!firstQuestion.ValidateAnswer(answer))
        {
            answer = Console.ReadLine().ToLower();
        }
        if (firstQuestion.VerifyAnswer(answer))
        {
            totalScore++;
        }
    }
}
请注意,我已经保留了代码部分不进行翻译,只翻译了注释和字符串内容。
英文:
The easiest way I can think of is to create a method to validate and a method to verify the answer within the questions class.
The while loop in the Main program below keeps calling the "ValidateAnswer" method until a valid input is received.
   class Questions
    {
        public string question;
        public string correctAnswer;
        private string userAnswer;
        public Questions(string aQuestion, string aCorrectAnswer)
        {
            question = aQuestion;
            correctAnswer = aCorrectAnswer;
        }
        public bool ValidateAnswer(string aUserAnswer)
        {
            if (aUserAnswer == "a" || aUserAnswer == "b" || aUserAnswer == "c")
            {
                return true;
            }
            Console.WriteLine("Invalid answer.");
            Console.WriteLine("Please choose between \"a\", \"b\" or \"c\".");
            return false;
        }
        public bool VerifyAnswer(string aUserAnswer)
        {
            return (aUserAnswer == correctAnswer);
        }
        static void Main(string[] args)
        {
            Questions firstQuestion = new Questions("1. You may drive off the paved roadway to pass another vehicle: ", "c");
            Console.WriteLine(firstQuestion.question);
            Console.WriteLine("----");
            Console.WriteLine("a) - If the shoulder is wide enough to accommodate your vehicle.");
            Console.WriteLine("b) - If the vehicle ahead of you is turning left.");
            Console.WriteLine("c) - Under no circumstances.");
            Console.Write("Your answer is: ");
            string answer = Console.ReadLine().ToLower();
            while (!firstQuestion.ValidateAnswer(answer))
            {
                answer = Console.ReadLine().ToLower();
            }
            if (firstQuestion.VerifyAnswer(answer))
            {
                totalScore++;
            }
        }
    }
答案2
得分: 0
作为对Tom Hazell精彩回答的补充,我想提供一个更通用的ValidateAnswer方法:
public bool ValidateAnswer(string aUserAnswer, string[] possibleAnswers)
{
    if (possibleAnswers.Contains(aUserAnswer))
    {
        return true;
    }
    Console.WriteLine("无效答案。");
    var options = string.Join(", ", possibleAnswers);
    Console.WriteLine($"请选择在{options}之间。");
    return false;
}
这个方法的思路是传递有效的答案字符数组,以应对问题可能有多于三个答案的情况。
然后你可以这样调用它:
string answer = Console.ReadLine().ToLower();
while (!firstQuestion.ValidateAnswer(answer, new string[] {"a", "b", "c"}))
{
    answer = Console.ReadLine().ToLower();
}
使用Contains需要引入using System.Linq;。
如果你坚持要有更友好的错误消息,你可以这样做:
var first = string.Join(", ", possibleAnswers.Take(possibleAnswers.Count() - 1));
var last = possibleAnswers[possibleAnswers.Count() - 1];
Console.WriteLine($"请选择在{first}和{last}之间。");
所有这些方法都仅在possibleAnswers包含多个元素时才有效,但对于一个问题只有1个或0个答案的情况是没有意义的。
英文:
As an addendum to Tom Hazell's fine answer I would make a more generic ValidateAnswer:
public bool ValidateAnswer(string aUserAnswer, string[] possibleAnswers)
{
    if (possibleAnswers.Contains(aUserAnswer)
    {
        return true;
    }
    Console.WriteLine("Invalid answer.");
    var options = string.Join(", ", possibleAnswers);
    Console.WriteLine($"Please choose between {options}");
    return false;
}
The idea is to pass the valid characters, if a question might have more than three answers.
Then you would call it like:
string answer = Console.ReadLine().ToLower();
while (!firstQuestion.ValidateAnswer(answer, new string {"a","b","c"}))
{
    answer = Console.ReadLine().ToLower();
}
Contains requires using System.Linq;.
If you insist on the nicer formulation of the error message, you can do:
var first = string.Join(", ", possibleAnswers.Take(possibleAnswers.Count() - 1));
var last = possibleAnswers[possibleAnswers.Count() - 1];
Console.WriteLine($"Please choose between {first} and {last}.");
All of this only works if possibleAnswers contains more than one element, but having 1 or 0 answers to a question wouldn't make sense.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论