Overload Method Error with Switch statement - c#

The application shall perform the selected menu math operation on the two entered numbers and display the answer.You must use methods for each math operation and a decision must be used to pick which method should be executed.
The application shall display an error message when a correct menu number is not entered. This is a decision where 1-5 are valid selections and everything else is “Invalid”.
The application shall not allow division by zero. Do not perform the divide operation if the second number variable is zero, but instead display an error message.
I have written the code but the program is showing the following error:
1. No overload for method AddNumber takes 0 arguments. this error is showing for all math operation methods inside the switch statements.
2. For DivideNumber method - not all code paths return a value
class Program
{
static void Main(string[] args)
{
double n1 = Convert.ToDouble(Console.ReadLine());
//string n2 = "";
double n2 = Convert.ToDouble(Console.ReadLine());
Console.Clear();
Console.WriteLine("Simple Calculator");
Console.WriteLine("\t 1) ADD");
Console.WriteLine("\t 2) SUBTRACT");
Console.WriteLine("\t 3) MULTIPLY");
Console.WriteLine("\t 4) DIVIDE");
Console.WriteLine("\t 5) QUIT");
Console.Write("Enter Selection: ");
int menuSelection =0;
// double total;
// menuSelection = Console.ReadLine();
switch (menuSelection)
{
case 1:
// total = Convert.ToInt32(AddNumbers("Results:"));
Console.WriteLine(AddNumbers(n1,n2));
break;
case 2:
Console.WriteLine(SubtractNumber(n1,n2));
break;
case 3:
Console.WriteLine(MultiplyNumber(n1,n2));
break;
case 4:
Console.WriteLine(DivideNumber(n1,n2));
break;
case 5:
break;
default:
Console.WriteLine("Invalid Selection !");
Console.ReadLine();
return;
}
//Ask user to enter two numbers
Console.WriteLine();
Console.Write("Enter Number 1:", n1);
// number1 = Console.ReadLine();
Console.Write("Enter Number 2:", n2);
// number2 = Console.ReadLine();
}
public static double AddNumbers(double number1, double number2)
{
return number1 + number2;
}
public static double SubtractNumber(double number1, double number2)
{
return number1 - number2;
}
public static double MultiplyNumber(double number1, double number2)
{
return number1 * number2;
}
public static double DivideNumber(double number1, double number2)
{
if (number1 == 0 && number2 == 0)
{
Console.WriteLine("Cannot Divide by Zero. Try Again");
return 0;
}
else
{
return number1 / number2;
}
}

1st mistake You are taking input after calling switch cases
2nd mistake your function have two parameters so pass them.
like DivideNumber(number1,number2) in your switch case
hope you understand
one thing i notice is you are taking input in string and your function takes double parameters so you need to convert string to double.
Give you idea use double to take input like double n1 = Convert.ToDouble(console.readline()); as input from console is string.

you are calling your function return AddNumbers();
but have declared it as public static double AddNumbers(double number1, double number2)
AddNumbers expected 2 numbers, you have passed 0.
You don't return anything from DivideNumbers, though you have declared it to return a double. public static double DivideNumber
The program makes no sense as it is. You are trying to do the operation before they've even given you the numbers. You should try to Rubber Duck this one yourself

This should do what your trying to accomplish.

Related

A problem with getting/printing answers in a C# calculator

I'm trying to make simple projects for learning C# and have tried to make a simple console calculator. I have only found this current error when getting to the getting/printing the answer bit when test-running my program, so I have no idea if there are any other errors/things that will or may not work or run properly/as intended. So if there are any of those, please let me know and if you want to you can fix them yourself. It only recognized the error when it reached that specific line of code, and otherwise will run the program until it reaches the error.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Calculator
{
class Program
{
static void Main(string[] args)
{
string num1;
string num2;
string condition;
string answer;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = Console.ReadLine();
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = Console.ReadLine();
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
answer = num1 + condition + num2;
Convert.ToInt32(answer);
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
answer = null;
num1 = null;
num2 = null;
condition = null;
}
}
}
}
When facing problems like this one - the routine is too complex to be tested:
if there are any other errors/things that will or may not work"
split routine into smaller ones: start extracting methods.
// Get integer value from user
public static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer value, please, try again.");
}
}
// Get character operator ('+', '-' etc.) from user
public static char ReadOperator(string title, string operators) {
while (true) {
if (!string.IsNullOrEmpty(title))
Console.WriteLine(title);
string input = Console.ReadLine().Trim();
if (input.Length == 1 && operators.Contains(input[0]))
return input[0];
Console.WriteLine("Sorry, not a valid operator, please, try again.");
}
}
Now we are ready to implement Main method:
static void Main(string[] args) {
while (true) {
int num1 = ReadInteger("Enter a number: ");
char op = ReadOperator("Enter a condition: ", "+-*/");
int num2 = ReadInteger("Enter your second number: ");
//TODO: I've skipped error handling (zero division, overflow)
int answer =
op == '+' ? num1 + num2 :
op == '-' ? num1 - num2 :
op == '*' ? num1 * num2 :
op == '/' ? num1 / num2 : 0;
Console.WriteLine($"{num1} {op} {num2} = {answer}");
//TODO: it's a right place here to ask user if (s)he wants to continue
Console.WriteLine();
}
}
You receive input (condition) as a string
cant do this : answer = num1 + condition + num2 because those variables are
string
you have to check that with switch , for example :
int num1 = 0, num2 = 0, answer = 0;
string condition;
Console.WriteLine("Calculator");
Console.WriteLine("For division, use /. For multiplication, use *.\n");
while (true)
{
Console.WriteLine("Enter a number: "); // gets first number to add in problem
num1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter a condition: "); // gets condition to add in problem
condition = Console.ReadLine();
Console.WriteLine("Enter your second number: "); // gets second number to add in problem
num2 = int.Parse(Console.ReadLine());
Console.WriteLine("Calculating..");
// converting strings to int and working out answer
Convert.ToInt32(num1);
Convert.ToInt32(num2);
// error is from here on (not sure if the Convert.ToInt32() code above causes errors)
switch (condition)
{
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
default:
Console.WriteLine("error : unknown operator");
break;
}
Console.WriteLine(answer);
// sets values to null after getting & printing answer (probably unnessessary)
}
You can't do this line because all the variables are strings and not the real values (e.g: num1 & num2 should ints/doubles... and condition should be a real operator).
answer = num1 + condition + num2;
Also, you can't do it because let's assume the user inputs the multiplication sign, and then the string of "*" is not equal to the sign of *.
Instead, you can do some switch-case statements to check the value of the condition variable. Also, you need to make sure num1 & num2 are numbers (you can parse/try-parse them to a number (int/double...)). You will also have to parse them to another variables as they are strings.
switch (condition)
{
case '*':
answer = numX * numY;
break;
case "/":
// Validate that numY is not 0 to avoid [DivideByZeroException][1]
answer = numX / numY;
break;
...
}
Note, it is just one way to do it and I just gave you a small example that might help you to continue.
I would also offer you to make a default case (in case that the input of the user is not something you expect, in this case, you may ask him again to write an input because the current input is invalid).

Getting a CS7036 error when passing variables between methods for a calculator (from a code test I found on the internet))

CS7036 C# There is no argument given that corresponds to the required formal parameter 'num1' of 'Calculator.Add(int, int, int)' same error for subtracting, divide and multiply.
The test rules said that it must have separate methods for each operation.
Trying to get back into coding after taking an unavoidably long break. Thought tests would be a good way to spark the code brain again.
Anyway,
I've tried different method parameters, such as passing the variables as references and as straight values, different ways of calling the methods, different security parameters (private, public, static etc).
I've spent 2 hours trawling different forums and scripting references to see if there was anything, but so far no luck. The test rules said that it must have separate methods for each operation.
I had an earlier error about the num1 2 and op being passed without identifiers as well, so that may be contributing here.
I do know this isn't the most effective or efficient way to make a calculator, however, it is how the test wants it to be done.
using System;
namespace code_challenge.Challenges
{
public class Calculator
{
/*
* Within this Calculator class you will need to create 4 methods.
* The four methods will relate to the basic functions of a calculator
and should be named:
*
* - Add
* - Subtract
* - Multiply
* - Divide
int num1 =0; int num2 =0; int ans =0; string op = " ";
public void Input(int num1,int num2,int ans,string op)
{
Console.WriteLine("Please enter the first number.");
num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the opperand.");
op = Console.ReadLine();
Console.WriteLine("Please enter the Second number.");
num2 = Convert.ToInt32(Console.ReadLine());
if (op == "+")
{
ERROR LINE Add();
}
if (op == "-")
{
ERROR LINE Sub();
}
if (op == "*")
{
ERROR LINE Mul();
}
if (op == "/")
{
ERROR LINE Div();
}
}
// Implement the add function below here
public void Add(int num1, int num2, int ans)
{
ans = num1 + num2;
Console.WriteLine("Your Answer is: " + ans);
}
// Implement the subtract function below here
public void Sub(int num1,int num2,int ans)
{
ans = num1 - num2;
Console.WriteLine("Your Answer is: " + ans);
}
// Implement the multiply function below here
public void Mul(int num1,int num2,int ans)
{
ans = num1 * num2;
Console.WriteLine("Your Answer is: " + ans);
}
// Implement the divide function below here
public void Div(int num1,int num2,int ans)
{
ans = num1 / num2;
Console.WriteLine("Your Answer is: " + ans);
}
}
}
No actual output due to the errors.
The expected output is that the operand input will throw the if statement, which will throw the appropriate operation and push ans into the console
I'll help you with Add op and you repeat this with other methods:
first,
if (op == "+")
{
Add(num1, num2);
}
second, change add method
public void Add(int num1, int num2)
{
ans = num1 + num2;
Console.WriteLine($"Your Answer is: {num1 + num2}");
}
Firstly, you are not passing any input arguments to the function. You should provide that.
Secondly, you do not need to have an input argument called ans in any of the function.
You can modify your function as following
public void Add(int num1,int num2){
int ans = num1+num2;
Console.WriteLine(ans);
}
Or you can return the value from the method for example:
public int Add(int num1,int num2){
int ans = num1+num2;
Console.WriteLine(ans);
return ans;
}
and in the input method, pass
Add(num1,num2)

Float/Double type input validation in C#

This is literally my first program I've ever written (started learning this past Monday); I am a total newbie.
My question is, how can I prevent exceptions from being thrown when a user enters an invalid character when the program prompts the user for fahreinheit or celsius entry (expecting a number)??? So for example, when a user enters "asfasd", the program throws an exception.
I did a lot of searching on the site before posting this, and I was successfully able to find other input validation questions, however, they were all concerning C and C++ and since I am such a newbie, I have a hard time with understanding those languages and how they relate to C#. Thank you. Please see code:
using System;
namespace Converter
{
class Program
{
static void Main()
{
float? FahrenheitInput = null;
double? CelsiusInput = null;
float? KilogramInput = null;
float? PoundsInput = null;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
FahrenheitInput = float.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
CelsiusInput = double.Parse(Console.ReadLine());
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static float? FahrenheitToCelsius(float? INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double? CelsiusToFahrenheit(double? INPUT)
{
return INPUT * 1.8 + 32;
}
}
}
You can either put it in Try-Catch block or use a while loop to validate the user input.
below is your code with a while loop which validates users input.
class Program
{
static void Main(string[] args)
{
double FahrenheitInput = 0;
double CelsiusInput = 0;
double KilogramInput = 0;
double PoundsInput = 0;
int UserChoice = 0;
do
{
Console.WriteLine("What would you like to convert? Enter the corresponding number.\n1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit\n3. Pounds to Kilograms\n4. Kilograms to pounds\n5. Exit program");
UserChoice = int.Parse(Console.ReadLine());
switch (UserChoice)
{
case 1:
Console.WriteLine("Enter the temperature in Fahreinheit, number only:");
while (!double.TryParse(Console.ReadLine(), out FahrenheitInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(FahrenheitInput + " degrees fahrenheit in Celsius is " + Program.FahrenheitToCelsius(FahrenheitInput) + "\n\n");
break;
case 2:
Console.WriteLine("Enter the temperature in Celsius, number only:");
while (!double.TryParse(Console.ReadLine(), out CelsiusInput))
{
Console.WriteLine("Invalid format, please input again!");
};
Console.Clear();
Console.WriteLine(CelsiusInput + " degrees Celius in fahrenheit is " + Program.CelsiusToFahrenheit(CelsiusInput) + "\n\n");
break;
case 5:
break;
default:
Console.WriteLine("This is not a valid entry. Please enter 1, 2, 3, 4, or 5.");
break;
}
} while (UserChoice != 5);
}
public static double FahrenheitToCelsius(double INPUT)
{
return (INPUT - 32) * 5 / 9;
}
public static double CelsiusToFahrenheit(double INPUT)
{
return INPUT * 1.8 + 32;
}
}
TryParse is your good friend here. In most scenarios, you should favor using TryParse than Parse. In your example, you can do something like:
int validInt;
int.TryParse(Console.ReadLine(), out validInt);
float validFloat;
float.TryParse(Console.ReadLine(), out validFloat);
Parse vs. TryParse
The easiest way, IMHO, to change the routine is to rewrite Parse into corresponding TryParse:
// UserChoice = int.Parse(Console.ReadLine());
UserChoice = int.TryParse(Console.ReadLine(), out UserChoice) ? UserChoice : -1;
...
A bit more complex (you have to convert float into float?)
// FahrenheitInput = float.Parse(Console.ReadLine());
float v;
FahrenheitInput = float.TryParse(Console.ReadLine(), out v) ? (float?) v : null;
The same scheme for CelsiusInput
// CelsiusInput = double.Parse(Console.ReadLine());
double d;
CelsiusInput = double.TryParse(Console.ReadLine(), out v) d (double?) d : null;
The underlying mechanic of the code is
We try to parse user input TryParse(Console.ReadLine()...
If parse succeeds (and thus TryParse returns true) we just return the out (parsed value).
If parse fails (and thus TryParse returns false) we return some special a value (-1 for UserChoice or null in case of FahrenheitInput or CelsiusInput)
P.S. in the first switch you have just case 1, case 2 and case 5; however, you've put "This is not a valid entry. Please enter 1, 2, 3, 4, or 5." in the error message. It seems, that you have to either implement case 3 and case 4 in the switch or edit the error message.
Use int.TryParse instead of int.Parse and float.tryParse instead of float.Parse
While all the answers provided seem to work, the question you asked was
how can I prevent exceptions from being thrown [..]
and I just want to point out that you do this by putting the part which throws the exception in an try-catch-block. What this does is it executes the code within try until an exception is beeing thrown and then passes this exceptions as a parameter to the catch-part where you can handle it:
EXAMPLE
do
{
try
{
// the code you already have
}
catch (Exception ex)
{
Console.WriteLine("This is no valid input (" + ex.Message + ")! Try again...");
}
} while (UserChoice != 5);
Of course preventing exceptions from beeing thrown at all in the first place is the better way (as all the other answers do suggest), but this approach works as well and ist more generic in case you run into a similar problem in the future. Using switch-case-statements for error-handling is quite common practice...

Trouble assigning value to integers inside a function to be referred to later - scope issue - I think

I'm learning C#. (6 hours in) I'm more comfortable with Ruby and Javascript and am finding C# fun, yet way tighter in what it will allow you to do, so I am rediscovering simple functions. I'm trying to build a simple calculator just to transition to the C# way of doing things and I keep hitting scope issues.
Here's the code. The NumSelect function is breaking it. I want a user to be able to type in 2 numbers in the console and then they'll be added. Once that works I'll create other math operations and throw in some logic to have the user select with operation they would like to do and then ask them for their inputs and then do the calculation.
The error is
calculator.cs(18,9): error CS0103: The name `number1' does not exist in the current context
and it's hitting it at very instance of number1 and number2 beyond the NumSelector function. So it seems like a scope issue, but I can't figure out the right approach for assigning these variables in a function so I only have to do it once.
using System;
class SimpleMath
{
public int Add(int number1, int number2)
{
int result = number1 + number2;
return result;
}
public int Subtract(int number1, int number2)
{
int result = number1 - number2;
return result;
}
//this function will assign the inputs to variables
public int NumSelect()
{
number1 = Console.ReadLine;
number2 = Console.ReadLine;
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
operation.NumSelect();
int result = operation.Add(number1, number2);
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
}
}
Well you need to decide whether these numbers are meant to be part of the state of your object or not. If they are, make them fields. If they're not, don't. In this case, I'd probably keep them as local variables and change your NumSelect code to simply return one number entered by the user - and call it twice:
public int NumSelect()
{
string line = Console.ReadLine();
return int.Parse(line);
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
int number1 = operation.NumSelect();
int number2 = operation.NumSelect();
int result = operation.Add(number1, number2);
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
}
You could change your whole class to make the values fields, and remove the parameters, like this:
class SimpleMath
{
private int number1;
private int number2;
public int Add()
{
int result = number1 + number2;
return result;
}
public int Subtract()
{
int result = number1 - number2;
return result;
}
public int SelectNumbers()
{
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
operation.NumSelect();
int result = operation.Add();
Console.WriteLine(
"{0} + {1} = {2}",
operation.number1,
operation.number2,
result);
}
}
This doesn't feel like the best approach to me - I'd take the earlier approach of using local variables in Main - but I wanted to show you the alternative. Note that you can only access operation.number1 in Main because the Main method is in the same type - that should raise warning bells for you.
Put your two numbers as class fields rather than methods'.
int number1 = 0, number2 = 0; //have them as class fields like this
public int NumSelect()
{
number1 = Console.ReadLine();
number2 = Console.ReadLine();
}
This way, you could access your number1 and number2 across different methods.
Method's fields/arguments are only valid within the method:
//number1 and number2 are method arguments, only accessible in the method
public int Add(int number1, int number2)
{
int result = number1 + number2;
return result;
}
//not accessible elsewhere
public int NumSelect() //number1 and number2 are unknown in this method
{
number1 = Console.ReadLine();
number2 = Console.ReadLine();
}
Just take two simple input from user in Main(). Like:
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
And then send it to your method Like:
int result = operation.Add(number1, number2);
otherwise declare the variables in the Field so that you can use them anywhere in the class.

How to use variables from one function in another?

I want to be able to use the "costOfCar" function in the "InterestPaid" function. I would appreciate any help.
namespace Functions9
{
class Program
{
static void Main(string[] args)
{
Double userCarCost, userDownPayment, userInterestRatePercentage, test; //declares "userCarCost" , "userDownPayment variable", "userInterestRatePercentage"
Console.WriteLine("This program will do some calculations for you about a car loan."); //explains the purpose and function of program to user
Console.WriteLine(); //adds an empty line
Console.WriteLine("What is the cost of your new car?"); //prompt user for input
userCarCost = Convert.ToDouble(Console.ReadLine()); //converts user input regarding car cost to double and stores in "userCarCost" variable
Console.WriteLine(); //adds an empty line
Console.WriteLine("How much money will you put as a down payment");
userDownPayment = Convert.ToDouble(Console.ReadLine()); //converts user input regarding down payment to double and stores in "userDownPayment" variable
Console.WriteLine();
Console.WriteLine("What is your interest rate percentage? Put a point before the number");
userInterestRatePercentage = Convert.ToDouble(Console.ReadLine()); //converts user input regarding interest rate to double and stores in "userInterestRatePercentage" variable
Console.WriteLine(); //adds an empty line
Console.WriteLine("How many years before you pay back the loan?");
CostOfCar(userCarCost, userDownPayment);
}
static double CostOfCar(double number1, double number2)
{
double costOfCar = number1 - number2; //"costOfCar" variable is determined by subtracting "userCarCost", "userDownPayment"
return costOfCar; // returns the cost of the car to the main method
}
static double InterestPaid(double number1, double number2)
{
double interestPaid = number1 * number2;
return interestPaid;
}
}
}
Just call it?
static double InterestPaid (double number1, double number2)
{
double interestPaid = number1 * number2 * CostOfCar(number1, number2);
return interestPaid;
}
Or with the correct formula you need.
(update according remark):
static double InterestPaid (double number1, double number2)
{
var costOfCar = CostOfCar(number1, number);
double interestPaid = number1 * number2 * costOfCar;
return interestPaid;
}
Btw, it is better to name functions with a verb, like CalculateCostOfCar.
You need something to capture the value.
In Main, instead of
CostOfCar(userCarCost, userDownPayment);
write
double cost = CostOfCar(userCarCost, userDownPayment);
Here, the variable cost is capturing the returned value from the function for later use.
static double InterestPaid (double number1, double number2)
{
var val=Program.CostOfCar(number1, number2);
double interestPaid = number1 * number2;
var total=val+interestpaid;
return total;
}

Categories

Resources