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 trial

C#

Arithmetic Calculator

using System; class math { static void Main() { var number=""; while (number != "QUIT") { Console.WriteLine("Please enter a number"); number=Console.ReadLine();

  if(number.ToUpper()== "QUIT")
  {
    break;
  }
  else
  {

    try
    {
      int number1 = Int32.Parse(number);
      Console.WriteLine("Please enter an operation");
      var operation= Console.ReadLine();

      Console.WriteLine("Please enter second number");
      int number2= Int32.Parse(Console.ReadLine());

      switch(operation)
      {
      case "+":
      Console.WriteLine (number1 + number2);
      break;
      case "-":
      Console.WriteLine (number1 - number2);
      break;
      case "*":
      Console.WriteLine (number1 * number2);
      break;
      case "/":
      Console.WriteLine (number1 / number2);
      break;
      }
    }
    catch(FormatException)
    {
          Console.WriteLine("Invalid input");
    }
   }
}

} } i wrote this done , how do i check the operation signs? i don't want to use if statements again and again. please tell me a better way to do it

3 Answers

Steven Parker
Steven Parker
231,172 Points

Using switch/case was a good idea.

I think your use of the switch/case statements is already better than chaining if statements. And your program seems to work well. Is there some other question you have about it?

the problem with this program is that when it asks to enter operation it does not check for invalid inputs, and it only checks for quit in the first question. is there a way to use that code again or do i need to write it again for the 2nd and 3rd input lines?

Steven Parker
Steven Parker
231,172 Points

You might put the part that reads input and checks it for "quit" in a separate function to make it easier to re-use. And checking for valid input will require a little bit of additional code.

thanx a lot