Click here to Skip to main content
15,894,287 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
Hi,

I have the following code which is a 10 question multiple choice quiz. I created a method to ask the questions, and a method for if a user submits an incorrect answer.

In the method for the incorrect answer, the user has the option to try again. If he chooses to do so I would like to display the question (which is stored in the other method again). How can I do this?

*P.S I know I asked the same question 10 times, when it works I will plug in the real questions and answers

Here is the code:


namespace Change_quiz_to_use_a_method
{
class Program
{
static void Main(string[] args)
{

string questions = "";
questions = displayQuestion(questions);
string usersAnswers = "";

usersAnswers = incorrectAnswer();
Console.WriteLine("the end of the game");
int score = 0;
Console.WriteLine("your score is " + score + "%");

/// template of question to check if the answer is valid and correct///
}
static string incorrectAnswer()
{

Console.WriteLine("wrong\ndo you want to try again (yes / no) ? ");
string again = Console.ReadLine();
if (again == "yes")
{

//Here I want the corresponding question from the method "getQuestion" to display
}
if (again == "no")
{
Console.WriteLine("next question");

}
else if (again != "yes")
{
Console.WriteLine("invalid entry ");
}
return "";
}

//Method to display questions using an array

static string displayQuestion(string questions)
{
//Array of questions
string[] question = new string[10];

question[0] = ("question 1. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[1] = ("question 2. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[2] = ("question 3. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[3] = ("question 4. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[4] = ("question 5. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[5] = ("question 6. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[6] = ("question 7. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[7] = ("question 8. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[8] = ("question 9. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");
question[9] = ("question 10. What color is the sky? \n a.blue \n b.green \n c.red \n d.black");


string[] correctAnswers = new string[10];

correctAnswers[0] = "a";
correctAnswers[1] = "b";
correctAnswers[2] = "c";
correctAnswers[3] = "d";
correctAnswers[4] = "a";
correctAnswers[5] = "b";
correctAnswers[6] = "c";
correctAnswers[7] = "d";
correctAnswers[8] = "a";
correctAnswers[9] = "d";



for (int i = 0; i < question.Length; i++)

{
Console.WriteLine(question[i]);
string input = Console.ReadLine();

int score = 0;

if (input == correctAnswers[i])
Console.WriteLine("Correct, excellent!");
score++;

string incorrect = "";
if (input != correctAnswers[i])
incorrect = incorrectAnswer();

}

return "";

}
}
}

Any help would be greatly appreciated (nothing fancy please, I am still pretty new to C#)!
Posted

This is going to be difficult, because I don't know how much you know about C# - not a lot it would seem, but we all have to start somewhere! :laugh:

Start by not storing your questions "inside a method" - store them at class level:
C#
class Program
    {
    private static string[] questions = new string[10] {
                                "question 1. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 2. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 3. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 4. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 5. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 6. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 7. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 8. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 9. What color is the sky? \n a.blue \n b.green \n c.red \n d.black",
                                "question 10. What color is the sky? \n a.blue \n b.green \n c.red \n d.black"};
    private static string[] correctAnswers = new string[10] {"a", "b", "c", "d", "a", "b", "c", "d", "a", "d"};
    static void Main(string[] args)
        {
Now you can access them from any part of your class, instead of just within the method. Later, you can remove the actual values, and load them questions and answers from a file - so you can change them without altering your application!

Then, add another class level integer variable which indexes into the two arrays and which specifies which question the user is answering:
C#
private int currentQuestionNumber = 0;
You can then use this to repeat questions and also move to the next.

Make sense?

[edit]Added the "static" keyword since your code is called from the static "Main" method[/edit]
 
Share this answer
 
v2
Comments
Member 12232520 28-Dec-15 12:54pm    
Huh - very interesting! Thanks a lot for taking the time to answer this!
OriginalGriff 28-Dec-15 13:57pm    
You're welcome!
BillWoodruff 29-Dec-15 4:01am    
+5 to counteract absurd down-vote
No, you cannot access anything declared/initialized in a method outside of it. The objects created in a method are stored on stack are inaccessible from outside; even if some reference heap memory, they are still inaccessible. Moreover, the stack frame of each method is removed from stack after the call, so the objects (for reference-type objects, it means the objects' reference parts) don't even exists; the stack memory will be reused.

You are going in wrong direction. Instead, you need to redesign your code. This can be said about all of your code, not about the problem you pointed out (which should not even be posed). You are doing something opposite to programming. Look at the repeated line assigning values to the elements of question and correctAnswers. The do the same thing. In programming, nothing is repeated. Your "yes", "no", "a", "b"… are all immediate constants hard-coded right in the code. You should not have such things. You did not defined any types; moreover, not any methods, except Main which you also did not define, because you got it from the project template. You don't understand the main concepts of programming, which is all about abstraction and reuse.

Overall, you need to start learning what programming is, from the very basics. I don't think asking questions here is a suitable way to learn it. You should first make yourself qualified by, say, studying some textbook, doing simple exercises as you go.

—SA
 
Share this answer
 
Comments
Member 12232520 28-Dec-15 12:53pm    
Thanks SA, I actually just started school and this is the homework after my sixth lesson, so like I said I am very new to programming. No need to bash the amateur, I'm sure at one point you were one also!
Sergey Alexandrovich Kryukov 28-Dec-15 14:53pm    
Yes, but believe me, I never wrote such things. Of course I've done a lot of stupid things, but not to the extent when I would repeat nearly the same line. :-)
It's not to "bash" anyone, but to point your mistakes so you could get to something reasonable sooner. You should better deal with criticism in a constructive way.
—SA
A few suggestions:

Since .NET 2.0, C# has a 'SortedList object which is handy for keeping a list of KeyValuePairs which you can access by index:
C#
class Program
{
public static SortedList<string,> QAndA;

static void Main(string[] args)
{
    QAndA = new SortedList<string,>
    {
        {"question 1. What color is the sky? \n a.blue \n b.green \n c.red \n d.black", 'a'},
        {"question 2. What color is red? \n a.blue \n b.green \n c.red \n d.black", 'c'}
    };
}
So, if you want to access the second question, and its answer:
C#
string question = QANDA.Keys[1];
char answer = QANDA.Values[1];
The virtue of using a Char for the "answers" is that you can use Console.ReadKey, and get ConsoleKeyInfo instance, rather than (using 'ReadLine) letting the user type whatever, which you then have to parse and validate. To get the 'Char value of a ConsoleKeyInfo instance: use its 'KeyChar property.

The other area you obviously need to work on is the "control flow" of your Console Application. How many times are you going to let the user repeat answering any one question ?

I suggest you consider a do/while loop as the basis:
C#
bool keepGoing = true;

ConsoleKeyInfo cki;
int howManyQuestions = QANDA.Count;
int currentQuestion = 0;
int numberOfTriesAllowed = 2;
int currentTry = 0;

do
{
    Console.WriteLine(QAndA.Keys[currentQuestion]);

    cki = Console.ReadKey(true);
    
    currentTry++;

    switch (cki.Key)
    {
        case ConsoleKey.Escape:
            // allow the user to quit the program at any time ?
            keepGoing = false;
            break;
        default:
            if (cki.KeyChar == QAndA.Values[currentQuestion])
            {
                // handle correct answer
                // for you to write

                currentquestion++;
                currentTry = 0;
            }
            else
            {
                // handle incorrect answer: allow user to try again ?
                // for you to write
                // if(currentTry ??????????????
            }
            break;
    }
    
    // finished ?             
    if(!keepGoing || currentQuestion == howManyQuestions)
    {
         // for you to write
         keepGoing = false;
    }

} while (keepGoing);

// do what is required to report the results of the test here
Here I have used the entry of an 'Escape character to trigger breaking out of the loop; this is rather standard.
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900