帮助,它无法正常运行,它返回未处理的异常 [英] help, it doesnt run correctly, it returns an unhandled exception

查看:70
本文介绍了帮助,它无法正常运行,它返回未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/*用于执行Hangman游戏的程序.该程序要求用户输入类别作为书籍/电影".根据类别
*只要提供,便会提取书名或类别名,并要求用户通过提供字符来猜出名字
*及其位置.*/

/*Program to play Hangman game. The program asks the user to enter a category as Book/Movie. Based on the category
* provided, a book name or category name is extracted and the user is asked to guess the name by giving the character
* and its position.*/

using System;
using System.IO;
using System.Threading;

namespace HANGMAN_GAME
{
    public class Hangman
    {
        string randomString, userString;
        int dataLength;
        string Category;
        string[] bookData = new string[5];
        string[] movieData = new string[5];
        int bookCount = 0, movieCount = 0;

        public Hangman()
        {
            FillNameValues();
        }

        //stores the movie names and Book names in respective strings
        private void FillNameValues()
        {
            string firstLine;
            //open file for reading
            try
            {
                StreamReader sRead = new StreamReader("C:\\TextTest.txt");
                sRead.BaseStream.Seek(0, SeekOrigin.Begin);
                //reading the file content
                firstLine = sRead.ReadLine();
                while (firstLine != null)
                {
                    //storing book names in the BookData array
                    if (firstLine.Substring(0, 1) == "B")
                    {
                        int stringStartPos = firstLine.IndexOf(':');
                        bookData[bookCount] = firstLine.Substring(stringStartPos + 1);
                        bookCount++;
                    }
                    //storing movie names in the MovieData array
                    else
                    {
                        int stringStartPos = firstLine.IndexOf(':');
                        movieData[movieCount] = firstLine.Substring(stringStartPos + 1);
                        movieCount++;
                    }
                    firstLine = sRead.ReadLine();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Invalid!");
            }
        }

        public int AcceptCategory()
        {
            try
            {
                //accepting user's choice in terms of category
                Console.WriteLine("Enter the category to play - Book/Movie");
                Category = Console.ReadLine();
                Category = Category.ToUpper();

                if (Category != "BOOK" && Category != "MOVIE")
                {
                    Console.WriteLine("Invalid Category....\n");
                    return 0;
                }
                else
                {
                    ExtractName();
                    return 1;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Errors!", e);
            }
        }

        public void ExtractName()
        {
            //new object of the random class
            Random RandGen = new Random();
            if (Category == "BOOK")
            {
                //randomly selecting a Book name from the array
                int Rnd = RandGen.Next(0, bookCount - 1);
                //calling play method
                randomString = bookData[Rnd];
            }
            else
            {
                //randomly selecting a Movie name from the array
                int Rnd = RandGen.Next(0, movieCount - 1);
                //calling play method
                randomString = movieData[Rnd];
            }
        }

        /*this method allows the user to give characters and displaying his status as to WIN or LOST */
        public void StartGame()
        {
            //calculating length of movie/book name
            dataLength = randomString.Length;

            char locateChar;
            int correctCnt = 0, inCorrectCnt = 0;
            int i, k;

            //declaring string to store user input
            char[] s = new char[randomString.Length];

            //loop to accept characters and its properties
            //loop allows user to attempt 2 times more than the total characters
            InitializeUserString();
            ShowUserInputString();
            if (Category == "BOOK")
            {
                Console.WriteLine("The total number of characters in the Book: {0}", randomString.Length);
                Console.WriteLine("The total number of characters you can enter to guess the name of Book: {0}", randomString.Length + 2);
            }
            else
            {
                Console.WriteLine("Total number of characters in the Movie: {0}", randomString.Length);
                Console.WriteLine("Total number of characters you can enter to guess the name of a Movie: {0}", randomString.Length + 2);
            }
            for (i = 1, k = 0; i <= dataLength + 2 || k == dataLength; i++)
            {
                if (correctCnt == dataLength || inCorrectCnt == dataLength)
                    break;
                Console.WriteLine("Enter the char");
                locateChar = Convert.ToChar(Console.ReadLine().ToLower());
                int foundPos = 0;
                int foundChar = 0;
                //to extract each character of a string
                foreach (char c in randomString)
                {
                    if (c == locateChar)
                    {
                        UpdateString(foundPos, locateChar.ToString());
                        k++;
                        foundChar = 1;
                    }
                    foundPos++;
                }
                if (foundChar == 0)
                {
                    Console.WriteLine("Wrong Attempt...Better Luck Next time!!HaHaHaHa!!!!!!\n");
                    inCorrectCnt++;
                }
                else
                {
                    correctCnt++;
                }

                ShowUserInputString();
                Console.WriteLine("Total Correst Attempts: {0}\t", correctCnt);
                Console.WriteLine("Total Incorrect Attempts: {0}\n", inCorrectCnt);
                if (k == dataLength)
                    break;
            }

            if (randomString == userString)
            {
                Console.WriteLine("You have Won!!!!!!!!!!!!\n");
            }
            else
            {
                Console.WriteLine("The Correct name is {0}", randomString);
                Console.WriteLine("HeHe....sadly, you have lost \n better luck next time");
            }
        }

        private void UpdateString(int fPos, string updateStr)
        {
            string beforeString, afterString;
            if (fPos != 0 && fPos != dataLength - 1)
            {
                if (fPos == 1)
                    beforeString = userString.Substring(0, 1);
                else
                    beforeString = userString.Substring(0, fPos);
                afterString = userString.Substring(fPos + 1, dataLength - (fPos + 1));
                userString = beforeString + updateStr + afterString;
            }

            if (fPos == 0)
            {
                afterString = userString.Substring(fPos + 1, dataLength - (fPos + 1));
                userString = updateStr + afterString;
            }
            if (fPos == dataLength - 1)
            {
                beforeString = userString.Substring(0, fPos);
                userString = beforeString + updateStr;
            }
        }

        public void InitializeUserString()
        {
            userString = "             ";
            for (int i = 0; i < dataLength; i++)
            {
                userString = userString.Insert(i, "*");
            }
        }

        public void ShowUserInputString()
        {
            Console.Clear();
            Console.WriteLine("Input Value: {0} \n\n", userString);
        }
    }

    class Game
    {
        static void Main(string[] args)
        {
            Console.Clear();
            Console.WriteLine("You have to complete the within 60 seconds!");
            Hangman obj = new Hangman();
            int returnVal = obj.AcceptCategory();
            if (returnVal == 1)
            {
                //obj.StartGame();
                Thread t = new Thread(new ThreadStart(obj.StartGame));
                t.Start(); //starting the new thread
                Thread.Sleep(60000); //Marking the Main thread sleep for 90 seconds
                try
                {
                    t.Abort();
                    Console.WriteLine("Time Over!!");
                } //killing the new thread
                catch (ThreadAbortException e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            Console.ReadLine();
        }
    }
}

推荐答案

首先,请点击上方的改进问题".不,您不必进行任何改进,只需查看HTML源代码即可了解应如何以HTML格式格式化C#源代码,以便在CodeProject帖子中看起来可读—我已将您的帖子稍作修正.

现在,从以下更改开始:代替此:
First, please click "Improve question" above. No, you don''t have to improve anything, just look at the source HTML code to see how the C# source code should be formatted in HTML to look readable in the CodeProject post — I fixed your post just a bit.

Now, start with the following change: instead of this:
catch (Exception e)
{
   Console.WriteLine("Invalid!");
}



至少写这样的东西:



write something like this, as a bare minimum:

catch (Exception e)
{
   Console.WriteLine(@"{0}: ""{1}""", e.GetType().FullName, e.Message);
}



您将学到更多有关您的问题的信息.

如果这还不够,请添加到输出e.Stacke.InnerException,提供所有内部异常的递归输出.

现在,正确放置该try-catch块.在每个线程堆栈的最顶部执行此操作.将启动线程顶部的一个块放在一个Main方法周围,将另一个try-catch块放在StartGame的最顶部附近.

这足以了解您的异常情况.无论如何,您是什么意思未处理的异常"?处理吗?

您真的需要做所有这些吗?如果仅使用调试器并找出问题,则不会.如果您自己无法解决问题,则此异常内容将帮助您改善问题:使用改善问题"添加异常转储;并指出源代码中if所在的源代码行.

是的,任何人都可以构建和运行您的代码,但是,如果您付出一点努力,您将有更多的变化来获得有效的帮助.另外,这种经验将在将来为您提供帮助.

祝你好运,

—SA
—SA



and you will learn a lot more about your problem.

If this is not enough, add to output e.Stack and e.InnerException, provide recursive output of all inner exceptions.

Now, place this try-catch block properly. Do it on the very top of the stack of each thread. Put one block of the top of starting thread, around just one Main method, another try-catch block — around the very top of StartGame.

That would be enough to learn all about your exception. Anyway, what do you mean "unhandled exception"? Handle it?

Do you really need to do all that? Not if you simply use debugger and find out the problem. If you fail to solve the problem yourself, this exception stuff will help you to improve your question: use "Improve question" to add exception dump; and indicate the source line where if goes in your source code.

Yes, anyone can build and run your code, but you have much more change to get effective help if you do this little effort. Also, this experience will help you in future.

Good luck,

—SA
—SA


这篇关于帮助,它无法正常运行,它返回未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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