The first two parameters seem to work but when I add the string I get an error (Line 17 cannot convert string to double). What am I missing here? From everything I've read in my book it seems like this should work so I'm guessing it's a stupid error but I've been looking up and down the code for the last 3 hours and haven't found anything. Thank you for reading this far!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication14
{
class Program
{
static void Main(string[] args)
{
SimpleCalc Calc = new SimpleCalc("{0.0}", "{0.0}", "{0}");
Console.WriteLine(Calc);
}
}
}
This is the class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication14
{
class SimpleCalc
{
public SimpleCalc(double num1, double num2, string oper)
{
Console.Write("Enter first integer: ");
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter operator (+,-,*, / or %)");
oper = Convert.ToString(Console.ReadLine());
Console.Write("Enter second integer: ");
num2 = Convert.ToDouble(Console.ReadLine());
if (oper == "+")
Console.Write("Answer is: {0}", num1 + num2);
if (oper == "-")
Console.Write("Answer is: {0}", num1 - num2);
if (oper == "*")
Console.Write("Answer is: {0}", num1 * num2);
if (oper == "/")
Console.Write("Answer is: {0}", num1 / num2);
if (oper == "%")
Console.Write("Answer is: {0}", num1 % num2);
Console.ReadKey();
}
}
}
The problem is that your constructor takes two doubles and a string:
public SimpleCalc(double num1, double num2, string oper)
But you're calling it with three strings:
SimpleCalc Calc = new SimpleCalc("{0.0}", "{0.0}", "{0}");
Change that to:
SimpleCalc calc = new SimpleCalc(0.0, 0.0, "{0}");
and it should be fine, in terms of compiling. (It's not good that you're interacting with the user in a constructor, and ignoring the values of the parameters that were passed in, but that's a different matter.)
Also note that I've changed the name of the local variable from Calc
to calc
to follow normal C# conventions.
See more on this question at Stackoverflow