Question

Let me start by showing you my code so far:

using System;
using System.Threading;
class MathQuiz
{
  static void Main() 
  {
   int score = 0;
   string preanswer;
   decimal answer = 0;
   Console.WriteLine("Welcome to Project5, a MathQuiz project.");
   Console.WriteLine("You will be asked 10 questions, and will have 30 seconds to read and answer each one.");
   Console.WriteLine("Press any key to begin.");
   Console.ReadKey(true);
   Console.WriteLine("What is 2 + 2?");
    Thread ask = new Thread (new ThreadStart (MathQuiz.prompt));
    ask.Start();
    Thread.Sleep(3000);
    //This is where I want to end the thread if it isn't already done.
    if (answer == 4)
    {
     score = score+1; //Here's where I don't know if my adding is correct.
    }
    Console.WriteLine("Press any key to move on to the next question!");
    Console.ReadKey(true);
  }

  static void prompt()
  {
   preanswer = (Console.ReadLine());
   if (!decimal.TryParse(preanswer, out answer))
  {
   Console.WriteLine("That wasn't even a number or decimal!");
  }
   else
       {
     answer = decimal.Parse(preanswer);
     }
  }
}

So, when I try and compile this code, I get CS0103 errors for preanswer and answer in the "prompt" method.

This leads to 3 questions:

  • What EXACTLY do I have to do to make preanswer and answer accessible to the "prompt" method?

  • Did I add 1 onto the score variable correctly?

  • How can I terminate a thread if it is running? (In this case, the "ask" thread wouldn't end until they typed an answer.)

Please just tell me what to change. I don't know coding words and terminology because I just started a few weeks ago. Please try to be as clear as possible.

Was it helpful?

Solution

      static string preanswer;
      static decimal answer = 0;

      static void Main() 
      {
       int score = 0;
       //string preanswer;
       //decimal answer = 0;
...

etc.

OTHER TIPS

To wait for the thread, use Join()... This will tell the thread which the function is called on to wait for the thread until it joins back:

ask.Join(int);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top