Reputation: 11
my do while function doesn't work in C# and i can't figure it out why, so here is the code :
I'm new to the community, the same code works well when is written is C++ 😔
using System;
namespace MiniCalculator
{
internal class Program
{
static void Main(string[] args)
{
double nb, nb1, result;
string ope, go;
do
{
Console.WriteLine("What do you want to do ? Choose the operator between these propositions : + - * / ");
ope = Console.ReadLine();
if (ope != "+" && ope != "-" && ope != "*" && ope != "/")
{
while (ope != "+" && ope != "-" && ope != "*" && ope != "/")
{
Console.WriteLine("Please, choose a right operator");
ope = Console.ReadLine();
}
}
else
Console.WriteLine("Operator choosen : ", ope);
Console.WriteLine("First number please.");
nb = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second number please.");
nb1 = Convert.ToInt32(Console.ReadLine());
if (ope == "+")
{
result = nb + nb1;
Console.WriteLine("Here is the result : " + result);
}
else if (ope == "-")
{
result = nb - nb1;
Console.WriteLine("Here is the result : " + result);
}
else if (ope == "*")
{
result = nb * nb1;
Console.WriteLine("Here is the result : " + result);
}
else if (ope == "/")
{
result = nb / nb1;
Console.WriteLine("Here is the result : " + result);
}
Console.WriteLine("Do you want to do another calculation ? (Y/n)");
go = Console.ReadLine();
if (go != "y" || go != "Y")
{
Environment.Exit(0);
}
} while (go == "y" || go == "Y");
}
}
}
Upvotes: 0
Views: 85
Reputation: 3956
if (go != "y" || go != "Y")
{
Environment.Exit(0);
}
this condition always exit your program..
try this:
if (go == "x" || go == "X")
{
Environment.Exit(0);
}
Upvotes: 0
Reputation: 71
Remove this code
if (go != "y" || go != "Y")
{
Environment.Exit(0);
}
This means that if go was y end the do while loop and exit the app.
Upvotes: 0
Reputation: 50190
You code summarizes to
do{
......
} while (go == "y" && go == "Y");
So this continues running when go == "y" and == "Y"
That can never happen, so it runs once
I think you mean
while (go == "y" || go == "Y");
You seem to think there is something magic going on here
look at this code
if (go != "y" || go != "Y")
{
Environment.Exit(0);
}
We should consider 3 possibilities for go values
go = "X"
go = "Y"
go = "y"
which one of these will make your program exit
well with "X"
if (go != "y" || go != "Y")
------true ----true
So exit
with "Y"
if (go != "y" || go != "Y")
-------true ---false
so exit
with "y"
if (go != "y" || go != "Y")
-------false ----true
so exit
There is no combination that does not exit.
You had the same problem with your while but inverted, it was always false
and I 100% guarantee that this is the same in c++
Upvotes: 3