Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialhhhg xhjc
758 PointsProgram does not quit even that I have break; used.
if user enters quit, it is supposed to exit.. pls help
using System;
namespace Calculator
{
class Program
{
static void Main()
{
while(true)
{
double num1;
Console.Write("Enter a number: ");
string number1 = Console.ReadLine();
while (!double.TryParse(number1, out num1))
{
Console.WriteLine("That is not a number");
Console.Write("Enter a number: ");
number1 = Console.ReadLine();
}
if(double.TryParse(number1, out num1)) {
Console.WriteLine("First number is " + num1);
}
else if(number1.ToLower() == "quit")
{
Console.WriteLine("Goodbye...");
break; // if user enters quit, it is supposed to exit.. pls help
}
//Prompt the user for an operation (+ - / *).
Console.Write("Enter an operation: ");
string operation = Console.ReadLine();
if(operation.ToLower() == "quit")
{
Console.WriteLine("Goodbye...");
}
double num2;
Console.Write("Enter second number: ");
string number2 = Console.ReadLine();
while(!double.TryParse(number2, out num2))
{
Console.WriteLine("That is not a number");
Console.Write("Enter second number: ");
number2 = Console.ReadLine();
}
if((double.TryParse(number2, out num2)))
{
Console.WriteLine("Second number is " + num2);
}
else if(number2.ToLower() == "quit")
{
Console.WriteLine("Goodbye...");
break;
}
if(operation == "+")
{
Console.WriteLine(num1 + num2);
} else if(operation == "-")
{
Console.WriteLine(num1 - num2);
} else if(operation == "*")
{
Console.WriteLine(num1 * num2);
} else if(operation == "/")
{
Console.WriteLine(num1 / num2);
} else if(operation == "^")
{
Console.WriteLine(Math.Pow(num1, num2));
} else
{
Console.WriteLine("---------------------\nSomething went wrong,\nplease check your input and try again");
}
}
}
}
}
2 Answers
Steven Parker
231,248 PointsYou have a 'break' for the outer loop, but the inner loop keeps running until it gets a number. You could add another break there:
while (!double.TryParse(number1, out num1))
{
if(number1.ToLower() == "quit") break; // <-- add this line
That should fix the immediate issue. But you still have a good bit of duplicated code, with a bit of refactoring you could make this program much more compact ("DRY").
hhhg xhjc
758 PointsThanks for answer! Yes, I also feel that my code is little bit badly organized...I will take care of it. Thanks!