无法达到while语句的结尾

时间:2015-10-10 21:08:12

标签: c# loops if-statement while-loop

我正在尝试创建一个游戏,提示用户输入所需的速度和角度,以确定随机生成的目标区域。我遇到的问题是我似乎无法到达while语句的末尾,它会询问玩家是否想再玩一次。我认为这是因为该线"继续;"在"猜测++;"。是否有工作允许用户继续猜测,直到他们得到正确答案并允许他们再次播放选项?

        int guess = 1;
        while (guess < 6)
        {
            Console.Write("Enter the initial velocity of the cannonball: ");
            double userVelocity = double.Parse(Console.ReadLine());
            Console.Write("Enter the angle of the cannon (between 0 and 90 degrees): ");
            double userAngle = double.Parse(Console.ReadLine());

            double targetDistance = distance - golf.Fire(userAngle, userVelocity);

            if (guess <= 5 && targetDistance >= 0.5 || targetDistance <= -0.5)
            {
                Console.WriteLine("Miss! Your shot hit " + golf.Fire(userAngle, userVelocity) + " meters. The target is " + targetDistance + " \n meters away.");
                Console.WriteLine();
                guess++;
                continue;
            }

            if (targetDistance <= 0.5 && targetDistance >= -0.5)
            {
                Console.WriteLine();
                Console.WriteLine("Hit! Congratulations! You hit the target!");
                //continue;
            }

            Console.WriteLine("Would you like to play again? (Y/N)");
            String secondAnswer = Console.ReadLine();
            secondAnswer = secondAnswer.Trim();
            String againResponse = secondAnswer.ToLower();

            if (againResponse == "y")
            {
                continue;
            }
            else if (againResponse == "n")
            {
                break;
            }
        }

2 个答案:

答案 0 :(得分:1)

更改

while (guess < 6)

while (guess <=6)

当更改为5时,change++会将其增加到6 但是,只有当变化小于6时,外循环条件才为真。将其更改为更小或相等将再次进入循环并进入Y / N部分

另外请注意,您可能想要更改此行

if (guess <= 5 && targetDistance >= 0.5 || targetDistance <= -0.5)

if (guess <= 5 && ( targetDistance >= 0.5 || targetDistance <= -0.5))

否则,您的情况会随时变为现实

targetDistance <= -0.5

答案 1 :(得分:1)

我建议使用For循环,而不是为您循环预定次数的任何情况编写While语句;这可以保护您免受遇到循环停止条件的常见错误。

这是一个(未经测试的)备用版本。它并不完美,但我做了一些调整,以帮助您的代码更具可读性,并且不易出错。我已经添加了评论来解释一些更改,但请询问是否有任何意义。

using System;

namespace StackOverflow
{
    class Program
    {

        Random randomNumberGenerator = new Random(DateTime.Now.Millisecond);

        static void Main(string[] args)
        {
            int maxGuesses = 5; //putting this in a variable allows you to amend the difficulty
            new Program(maxGuesses);
            Console.WriteLine("Done; press enter to end");
            Console.ReadLine();
        }

        //Kicks off the game
        //On completion asks if the user wants to play again
        //If so relaunches the game; if not exits.
        Program(int maxGuesses)
        {
            bool playAgain = true;
            while (playAgain)
            {
                Play(maxGuesses);
                playAgain = PromptToPlayAgain();
            }
        }

        //returns: 
        //- true if user enters Y
        //- false if user enters N
        //if user enters anything else, keeps asking
        bool PromptToPlayAgain() 
        {
            String againResponse = "";
            while (againResponse != "y" && againResponse != "n")
            {
                Console.WriteLine("Would you like to play again? (Y/N)");
                againResponse = Console.ReadLine().Trim().ToLower();
            }
            return againResponse == "y";
        }

        double GetVelocity()
        {
            Console.Write("Enter the initial velocity of the cannonball: ");
            return double.Parse(Console.ReadLine());
        }
        double GetAngle()
        {
            Console.Write("Enter the angle of the cannon (between 0 and 90 degrees): ");
            return double.Parse(Console.ReadLine());
        }

        //generate a random distance
        //returns a double where 100 <= d < 300
        double GetRangeDistance()
        {
            return randomNumberGenerator.Next(1000, 3000)/10; //returns
        }

        //return true if the person's within .5 meters of the target; else false
        bool CheckWinCondition(double targetDistance)
        {
            return targetDistance <= 0.5 && targetDistance >= -0.5;
        }
        //display message if successful
        void ReportHit()
        {
            Console.WriteLine();
            Console.WriteLine("Hit! Congratulations! You hit the target!");
        }
        //display message if missed
        void ReportMiss(double shotDistance, double targetDistance)
        {
            Console.WriteLine("Miss! Your shot hit {0} meters. The target is {1} meters away.", shotDistance, targetDistance); //use {n} string formatting to put your numbers into your string
            Console.WriteLine(); //NB: the blank line's the other way round to how you have it in ReportHit
        }
        //the game
        void Play(int maxGuesses)
        {
            Golf golf = new Golf();
            double distance = GetRangeDistance();
            for (int guess = 1; guess <= maxGuesses; guess++) //use a for loop instead of while as we want to iterate a given number of times
            {
                double userVelocity = GetVelocity();
                double userAngle = GetAngle();
                //since we're using different variables for targetDistance and distance I assume 
                //that each shot's being taken from the tee; i.e. the player doesn't move to 
                //where the ball lands.
                //Also I assume all shots go in a straight line between the tee and the hole
                //and that angle is just up/down; not left/right, as otherwise the calc for
                //target distance is off.
                double shotDistance = golf.Fire(userAngle, userVelocity); //store this in a variable so we can reuse the result without recalculating
                double targetDistance = distance - shotDistance;
                if (CheckWinCondition(targetDistance)) 
                {
                    ReportHit();
                    break; //exits the for loop early
                }
                else
                {
                    ReportMiss(targetDistance, shotDistance);
                }
            }
        }

    }
}