Home > Enterprise >  While loop not looping - C#
While loop not looping - C#

Time:08-12

internal class Program
{
    private static void Main(string[] args)
    {
        bool end = false;

        while (end != true)
        {
            Random rnd = new Random();
            int rps = rnd.Next(1, 4);

            Console.WriteLine("Rock Paper Scissors");
            string input = Console.ReadLine().Trim(); 

            if (input == "Rock" && rps == 1)
                Console.WriteLine("You Win");
            end = true;

            if (input == "Rock" && rps == 2)
                Console.WriteLine("You Lose");
            end = true;

            if (input == "Rock" && rps == 3)
                Console.WriteLine("Tie, play again");
        }
    }
}

In this program, I am trying to create a rock paper scissors program however, when it rps == 3 and its a tie, instead of starting from the beginning of the while statement, it does not do anything - regardless of the input it stops.

What is wrong?

CodePudding user response:

As mentioned in comment, you didn't use braces {} properly. I also made it a bit better, so you can use this :

internal class Program
{
    private static void Main(string[] args)
    {
        bool end = false;
        Random rnd = new Random();
        int rps;
        string input;
        
        while (end != true)
        {
            end = true;
            rps = rnd.Next(1, 4);

            Console.WriteLine("Rock Paper Scissors");
            input = Console.ReadLine().Trim(); 

            if (input == "Rock" && rps == 1)
                Console.WriteLine("You Win");

            if (input == "Rock" && rps == 2)
                Console.WriteLine("You Lose");

            if (input == "Rock" && rps == 3)
            {
                Console.WriteLine("Tie, play again");
                end = false;
            }
        }
    }
}

CodePudding user response:

You did it wrong. You didn't use brackets.

if (condition) 
{ 
   // more than one line
} 

if (condition) 
 //single line

Please try it like this;

if (input == "Rock" && rps == 1)
{
    Console.WriteLine("You Win");
    end = true;
}

if (input == "Rock" && rps == 2)
{
    Console.WriteLine("You Lose");
    end = true;
}

CodePudding user response:

You need to wrap the if statement in a block

if (input == "Rock" && rps == 1)
   Console.WriteLine("You Win");
   end = true; // this line is always executed

Is not the same as

if (input == "Rock" && rps == 1)
{
   Console.WriteLine("You Win");
   end = true;
}
  •  Tags:  
  • c#
  • Related