Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - program not exiting

Tags:

c#

exit

just started using C#, and this may be just a simple fix but I can't seem to see it. Once the program executes the first time (after adding two numbers), the user is prompted to input yes or no as an exit condition. When I type in 'no', the program will loop again.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            bool again = false;
            while (!again)
            {
                Console.WriteLine("C# Basic Calcuator");
                Console.WriteLine("Please enter two numbers to be added: ");
                Console.WriteLine("Number 1: ");

                int result;
                int a = Convert.ToInt32(Console.ReadLine());


                Console.WriteLine("Number 2: ");
                int b = Convert.ToInt32(Console.ReadLine());

                Console.WriteLine("Result: ");
                result = a + b;

                //print result
                Console.WriteLine(result);

                //potential exit condition
                Console.WriteLine("Would you like to calculate again?");
                if(Console.ReadLine() == "no")
                {
                    again = false;
                }
                else
                {
                    again = true;
                }

            }



        }
    }
}

Any help is greatly appreciated!

like image 423
xtheking Avatar asked Mar 28 '26 05:03

xtheking


2 Answers

Change the top 2 lines to the following:

bool again = true;
while (again)
like image 80
Melbz Avatar answered Mar 29 '26 19:03

Melbz


change

while (!again)

with

while (again)

when user types no, again is set to false; so in the while loop again is negated which results in continuation of while loop.

by the way, you need to change

bool again = false;

to

bool again = true;
like image 35
daryal Avatar answered Mar 29 '26 18:03

daryal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!