I wrote out a simple calculator that uses multiple methods.
This is what I wrote out, but is there a better/more efficient way to write this code?
Suggestions would be helpful.
I want to use multiple methods and have everything visible in the main method. I know it looks silly and can be done in a much more simple way, but I'm trying to explain this to people who are new to C# and are beginning to learn about methods.
{
Console.WriteLine("Please input two numbers");
int num1 = Convert.ToInt32(Console.ReadLine());
int num2 = Convert.ToInt32(Console.ReadLine());
int answer1 = Sum(num1, num2);
int answer2 = Sub(num1, num2);
int answer3 = Mult(num1, num2);
double answer4 = Div(num1, num2);
Console.WriteLine("Sum: {0}\n"+"Difference: {1} \n"+"Multiplication: {2} \n"+"Division: {3} \n", answer1, answer2, answer3, answer4);
}
public static int Sum(int num1, int num2)
{
return num1 + num2;
}
public static int Sub(int num1, int num2)
{
return num1 - num2;
}
public static int Mult(int num1, int num2)
{
return num1 * num2;
}
public static double Div(int num1, int num2)
{
return num1 / num2;
}
}
You can create a small menu to choose what you want to do.
The following code is a code example, and you can refer to it.
class Program
{
static void Main(string[] args)
{
string a = string.Empty;
do
{
Console.WriteLine("Please input two numbers");
int num1 = Convert.ToInt32(Console.ReadLine());
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please choose the following you want to do");
Console.WriteLine("1. Add");
Console.WriteLine("2. Minus");
Console.WriteLine("3. Mult");
Console.WriteLine("4. Div");
int number = Convert.ToInt32(Console.ReadLine());
switch (number)
{
case 1:
Console.WriteLine("Your result is" + Add(num1, num2));
break;
case 2:
Console.WriteLine("Your result is" + Minus(num1, num2));
break;
case 3:
Console.WriteLine("Your result is" + Mult(num1, num2));
break;
case 4:
Console.WriteLine("Your result is" + Div(num1, num2));
break;
default:
Console.WriteLine("Please input again");
break;
}
a = Console.ReadLine();
}
while (a == "y");
}
public static int Add(int num1, int num2)
{
return num1 + num2;
}
public static int Minus(int num1, int num2)
{
return num1 - num2;
}
public static int Mult(int num1, int num2)
{
return num1 * num2;
}
public static double Div(int num1, int num2)
{
return num1 / num2;
}
}
The only possible improovement I could think off, is making those operators. But the existing Operators for Int alraedy cover all those cases and it only works for your self-created types anyway.
As you are on the console. A do...while loop with a swtich/case as menu might be usefull for the programm flow. But not anything else I can think off.
Math is even one of the rare examples where static methods are not missplaced/overused.
Only a small terminology nitpick: Those are functions, not methods:
functions return a value
methods do not
However I have not see a langauge that actually differentaites between the two in ages. Delphi or VB might have this Keyword distinction.
Related
First of all i'm new to programming and just finished the Course on SoloLearn about C#.
I do understand the core principal of try-catch blocks but i can't figure out how to correctly implement this in to my code(code shown below).
class Program
{
static void Main(string[] args)
{ //create object of Class Calculator
Calculator calc = new Calculator();
//take user input and store in num1 and print it to screen
try{
double num1 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nnumber1: " + num1);
double num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("\nnumber2: " + num2);
//take operator as input and print it to screen
string operand = Console.ReadLine();
Console.Write("\noperator: " + operand);
//check if operator from user input is equal to one of the 4 calculation methods in Calculator Class
Console.Write("\nresult: ");
if(operand == "+"){
Console.WriteLine(calc.Addition(num1, num2));
}
else if(operand == "-"){
Console.WriteLine(calc.Subtraction(num1, num2));
}
else if(operand == "*"){
Console.WriteLine(calc.Multiplication(num1, num2));
}
else{
Console.WriteLine(calc.Division(num1, num2));
}
}
catch(DivideByZeroException){
Console.WriteLine("can't divide by zero");
}
catch(Exception e){
Console.WriteLine("An error occurred. Only integers are allowed!");
}
}
}//class Calculator with methods for 4 simple calculations
class Calculator{
private double number1;
private double number2;
private double res;
public double Addition(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 + num2;
return res;
}
public double Subtraction(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 - num2;
return res;
}
public double Multiplication(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 * num2;
return res;
}
public double Division(double num1, double num2){
this.number1 = num1;
this.number2 = num2;
this.res = num1 / num2;
return res;
}
}
So i want my simple calculator to handle the exception "DivideByZero" and "Exception e" -> if the input was not an integer.
When i test the DivideByZero Exception with an example input of 4/0, the programm returns "Infinite" as a result instead of the code from the catch block.
I guess the "Infinite" result comes from the if-statements inside the try-catch block but i'm not sure.
I searched multiple sites, similar posts on stackoverflow and read the microsoft documentation for c# about try-catch blocks but i just can't figure it out.
Sorry if my code sample is too big but i think this is the best way to understand my mess of code.
Thank you in advance for the quick reply !
Change fragment
else {
Console.WriteLine(calc.Division(num1, num2));
}
into
else {
Console.WriteLine(num2 != 0
? $"{calc.Division(num1, num2)}"
: "can't divide by zero");
}
Since floating point division doesn't throw exception but returns NaN, PositiveInfinity and NegativeInfinity:
0.0 / 0.0 == double.NaN
1.0 / 0.0 == double.PositiveInifinity
-1.0 / 0.0 == double.NegativeInfinity
There is nothing wrong with your try catch. If you divide a double by zero, you don't get an exception. You get Double.PositiveInfinity as result in your case.
The DivideByZeroException is only thrown for integer or decimal data types.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code
Basic Calculator Using 2 methods
1 is the main method
2 is the operator
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int num1;
int num2; //Variables for equation
string op;
//int Answer;
Console.Write("Enter the first number : ");
num1 = Convert.ToInt32(Console.ReadLine());
//User input for equation
Console.Write("Now enter your second number : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Ok now enter your operation ( x , / , +, -) ");
op = Console.ReadLine();
Methods1(); // This is the error, The error says
// There's no argumen given that corresponds
}
static int Methods1(int num1, int num2, string op)
{
if (op == "+")
{
return num1 + num2;
}
else if (op == "-")
{
return num1 - num2;
}
else if (op == "/")
{
return num1 / num2;
}
else if (op == "*")
{
return num1 * num2;
}
else
{
Console.WriteLine("Invalid Operator");
return 0;
}
}
}
}
You have called the Methods1() method without arguments. Change the code to the following:
using System;
namespace Test_app_1
{
class Program
{
static void Main(string[] args)
{
int num1;
int num2; //Variables for equation
string op;
int Answer;
Console.Write("Enter the first number : ");
num1 = Convert.ToInt32(Console.ReadLine());
//User input for equation
Console.Write("Now enter your second number : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Ok now enter your operation ( * , / , +, -) ");
op = Console.ReadLine();
Answer = Methods1(num1, num2, op); // Now no error...
Console.WriteLine(Answer + "\nPress any key to exit..."); //You forgot to add Console.Writeline
Console.Read(); //Also forgot Console.Read
}
static int Methods1(int num1, int num2, string op)
{
if (op == "+")
{
return num1 + num2;
}
else if (op == "-")
{
return num1 - num2;
}
else if (op == "/")
{
return num1 / num2;
}
else if (op == "*")
{
return num1 * num2;
}
else
{
Console.WriteLine("Invalid Operator");
return 0;
}
}
}
}
Hello im trying to code a scientific calculator, im new to c# and im having some problems with trying to implement an option where at the end of a calculation I can ask the user whether they want to restart the calculator.
This is what i've got currently:
namespace Scientific_Calculator_Project
{
class SuperCalculator
{
static void Main(string[] args)
{
// Declaring my variables
double num1, num2, answer;
string operation;
string exitOption;
// Asking the user for the operation, to call a function to perform that operation
Console.Write("Please enter an operation you wish to perform (+, -, /, *, ^, ^1/2, !, f-1): ");
operation = Console.ReadLine();
// Prompting the input of the first number
Console.Write("Please enter your first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
// Prompting the input of the second number
Console.Write("Please enter your second number (if no other number is needed please enter ): ");
num2 = Convert.ToDouble(Console.ReadLine());
// Using if statements to decide which function to call based on the operation, as well as an error message for an invalid value
if (operation == "+")
{
Console.WriteLine(Sum(num1, num2));
}
else if (operation == "-")
{
Console.WriteLine(Minus(num1, num2));
}
else if (operation == "/")
{
Console.WriteLine(Divide(num1, num2));
}
else if (operation == "*")
{
Console.WriteLine(Multi(num1, num2));
}
else if (operation == "^")
{
Console.WriteLine(ToPower(num1, num2));
}
else if (operation == "^1/2")
{
Console.WriteLine(Sqroot(num1));
}
else if (operation == "!")
{
Console.WriteLine(Factorial(num1));
}
else if (operation == "f-1")
{
Console.WriteLine(ToInverse(num1));
}
else if (operation == "log")
{
Console.WriteLine(ToLog(num1));
}
else if (operation == "rad")
{
Console.WriteLine(ToRadian(num1));
}
else
{
Console.WriteLine("Invalid operation");
}
Console.WriteLine("Would you like to continue? (Yes/No)");
exitOption = Console.ReadLine();
Console.ReadLine();
// Function for addition (Sum)
static double Sum(double num1, double num2)
{
double resultofSum = num1 + num2;
return resultofSum;
}
// Function for subtraction (Minus)
static double Minus(double num1, double num2)
{
double resultofMinus = num1 - num2;
return resultofMinus;
}
// Function for division (Divide)
static double Divide(double num1, double num2)
{
double resultofDivide = num1 / num2;
return resultofDivide;
}
// Function for multiplication (Multi)
static double Multi(double num1, double num2)
{
double resultofMulti = num1 * num2;
return resultofMulti;
}
// Function for raising x (num1) to the power of y (num2)
static double ToPower(double num1, double num2)
{
double resultofToPower = Math.Pow(num1, num2);
return resultofToPower;
}
// Function for square root of x (num1)
static double Sqroot(double num1)
{
double resultofSqroot = Math.Sqrt(num1);
return resultofSqroot;
}
// Function for finding factorial of x (num1),
static double Factorial(double num1)
{
double factorial = 1;
if (num1 < 0)
{
Console.WriteLine("Error: Can't find factorial of a negative number");
return 0;
}
else if (num1 <= 1)
{
return 1;
}
else
{
for (double i = 1; i <= num1; i++)
{
factorial = factorial * i;
}
Console.WriteLine("{0}! = {1}", num1, factorial);
return factorial;
}
}
// Function for obtaining the inverse of x (1/num1)
static double ToInverse(double num1)
{
double ToInverse = 1 / num1;
return ToInverse;
}
// Function for obtaining the base 10 log of x (num1)
static double ToLog(double num1)
{
double Tolog = Math.Log10(num1);
return Tolog;
}
// Function for converting an angle x (num1) from degrees to radians
static double ToRadian(double num1)
{
double Toradian = (num1 * (Math.PI)) / 180;
return Toradian;
}
}
}
}
Lots of ways, but here is an example of one way. The code below will loop each time the user hits a key, unless they hit the "Enter" key, in which case it will drop out and end:
static void Main(string[] args)
{
ConsoleKeyInfo keyInfo;
bool loop = true;
while (loop)
{
//do your stuff here
//...
//then do this:
keyInfo = Console.ReadKey();
if(keyInfo.Key == ConsoleKey.Enter)
{
loop = false;
}
else
{
loop = true;
}
}
}
Please see the changes below
using System;
namespace Scientific_Calculator_Project
{
class SuperCalculator
{
static void Main(string[] args)
{
// Declaring my variables
double num1, num2, answer;
string operation;
string exitOption;
while (true)
{
// Asking the user for the operation, to call a function to perform that operation
Console.Write("Please enter an operation you wish to perform (+, -, /, *, ^, ^1/2, !, f-1): ");
operation = Console.ReadLine();
// Prompting the input of the first number
Console.Write("Please enter your first number: ");
num1 = Convert.ToDouble(Console.ReadLine());
// Prompting the input of the second number
Console.Write("Please enter your second number (if no other number is needed please enter ): ");
num2 = Convert.ToDouble(Console.ReadLine());
// Using if statements to decide which function to call based on the operation, as well as an error message for an invalid value
if (operation == "+")
{
Console.WriteLine(Sum(num1, num2));
}
else if (operation == "-")
{
Console.WriteLine(Minus(num1, num2));
}
else if (operation == "/")
{
Console.WriteLine(Divide(num1, num2));
}
else if (operation == "*")
{
Console.WriteLine(Multi(num1, num2));
}
else if (operation == "^")
{
Console.WriteLine(ToPower(num1, num2));
}
else if (operation == "^1/2")
{
Console.WriteLine(Sqroot(num1));
}
else if (operation == "!")
{
Console.WriteLine(Factorial(num1));
}
else if (operation == "f-1")
{
Console.WriteLine(ToInverse(num1));
}
else if (operation == "log")
{
Console.WriteLine(ToLog(num1));
}
else if (operation == "rad")
{
Console.WriteLine(ToRadian(num1));
}
else
{
Console.WriteLine("Invalid operation");
}
Console.WriteLine("Would you like to continue? (Yes/No)");
exitOption = Console.ReadLine();
if(exitOption.ToLower() == "no")
{
break;
}
// Function for addition (Sum)
static double Sum(double num1, double num2)
{
double resultofSum = num1 + num2;
return resultofSum;
}
// Function for subtraction (Minus)
static double Minus(double num1, double num2)
{
double resultofMinus = num1 - num2;
return resultofMinus;
}
// Function for division (Divide)
static double Divide(double num1, double num2)
{
double resultofDivide = num1 / num2;
return resultofDivide;
}
// Function for multiplication (Multi)
static double Multi(double num1, double num2)
{
double resultofMulti = num1 * num2;
return resultofMulti;
}
// Function for raising x (num1) to the power of y (num2)
static double ToPower(double num1, double num2)
{
double resultofToPower = Math.Pow(num1, num2);
return resultofToPower;
}
// Function for square root of x (num1)
static double Sqroot(double num1)
{
double resultofSqroot = Math.Sqrt(num1);
return resultofSqroot;
}
// Function for finding factorial of x (num1),
static double Factorial(double num1)
{
double factorial = 1;
if (num1 < 0)
{
Console.WriteLine("Error: Can't find factorial of a negative number");
return 0;
}
else if (num1 <= 1)
{
return 1;
}
else
{
for (double i = 1; i <= num1; i++)
{
factorial = factorial * i;
}
Console.WriteLine("{0}! = {1}", num1, factorial);
return factorial;
}
}
// Function for obtaining the inverse of x (1/num1)
static double ToInverse(double num1)
{
double ToInverse = 1 / num1;
return ToInverse;
}
// Function for obtaining the base 10 log of x (num1)
static double ToLog(double num1)
{
double Tolog = Math.Log10(num1);
return Tolog;
}
// Function for converting an angle x (num1) from degrees to radians
static double ToRadian(double num1)
{
double Toradian = (num1 * (Math.PI)) / 180;
return Toradian;
}
}
}
}
}
using System;
namespace Myprog
{
class Myprog
{
int num1;
int num2;
public void Getdata()
{
Console.WriteLine("enter two numbers");
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
}
public void Showdata()
{
Console.WriteLine("First value {0} Second value {1}",num1,num2);
}
static void Main(string[] args)
{
Myprog C=new Myprog();
C.Getdata();
C.Showdata();
}
}
}
=>in this program always assign value 0, please give me suggestion how to solve this program and I want to run to this program in this manner.
Thank you.
Your num1 and num2 as a fields are completely different your num1 and num2 as a local variables.
You can assign those variables into your fields in your Getdata method like;
this.num1 = num1;
this.num2 = num2;
like;
int num1;
int num2;
public void Getdata()
{
Console.WriteLine("enter two numbers");
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
this.num1 = num1;
this.num2 = num2;
}
public void Showdata()
{
Console.WriteLine("First vale {0} Second value {1}",num1,num2);
}
static void Main(string[] args)
{
Myprog C=new Myprog();
C.Getdata();
C.Showdata();
}
In the Getdata() method you define new local variables named num1 and num2 and assign values to them.
Remove the int from each line to assign values to fields num1 and num2 instead of creating locals.
num1 = int.Parse(Console.ReadLine());
num2 = int.Parse(Console.ReadLine());
this is basically a dumbed down version of what I want to accomplish.
I am trying to tell the program to pass the two methods from different functions to the final one but it says they do not exist in the current context even though I've tried to pass them in Num1 and Num2
static void Main(String[] args)
{
int Option;
DisplayMenu();
Option = GetUserOption();
while (Option != 0)
{
switch (Option)
{
case 1:
Num1();
break;
case 2:
Num2();
break;
case 3:
Overall(Num3, Num4);
break;
}
}
}
static void DisplayMenu()
{
Console.WriteLine("1. Num1 2.Num2 3.Overall");
}
static int GetUserOption()
{
int Option;
Console.WriteLine("Pick choice");
Option = Convert.ToInt32(Console.ReadLine());
return Option;
}
static int Num1()
{
int Num3;
Console.WriteLine("Enter your first number");
Num3 = Convert.ToInt32(Console.ReadLine());
return Num3;
}
static int Num2()
{
int Num4;
Console.WriteLine("Enter your second number");
Num4 = Convert.ToInt32(Console.ReadLine());
return Num4;
}
public static int Overall(int Num3, int Num4)
{
int Overall;
Console.WriteLine("This will add the two together");
Overall = Overall + Num3 + Num4;
Console.WriteLine(Overall);
return Overall;
}
It is still telling me that the params don't exist in the current context.
EDIT: Moved the params into Overall case but still the same error message.
I can see a handful of problems:
In Main, you haven't declared the variables Num3 and Num4, so the compiler is unhappy that you're trying to pass them to the Overall method. You should declare them before your loop (and initialise them to some default value).
iNum3 and iNum4 don't exist in the Overall method. You've named the arguments as Num3 and Num4.
You've declared a variable called Overall in the method Overall but haven't initialised it, so when you try to do Overall + iNum3 + iNum4, the variable doesn't yet have a value. It's simpler to write int Overall = Num3 + Num4.
First off thats not how you would do such a thing its very convoluted and doesnt make sense (took me a while to figure out what you are doing). I still dont exactly know if you are trying to do what i am thinking.
Anyways my guess is you want to add two numbers together and give the user a option at every step if he wants to enter number 1, number 2 or show the current result? Here is a solution where i tryed to keep your style(incase you are learing about switch and function) while maintaining the code. Its still way to "complex" for whats it doing
static void Main(String[] args)
{
int option = 1;
int num1 = 0;
int num2 = 0;
int sum = 0;
DisplayMenu();
while (option != 0)
{
option = GetUserOption();
switch (option)
{
case 1:
num1 = getNum(option);
break;
case 2:
num2 = getNum(option);
break;
case 3:
Overall(num1, num2, sum);
break;
}
}
}
static void DisplayMenu()
{
Console.WriteLine("1: Num1, 2: Num2, 3: Overall, 0: Exit");
}
static int GetUserOption()
{
Console.WriteLine("Pick choice");
return Convert.ToInt32(Console.ReadLine());
}
static int getNum(int option)
{
if (option == 1)
Console.WriteLine("Enter your first number");
else
Console.WriteLine("Enter your second number");
return Convert.ToInt32(Console.ReadLine());
}
static int Overall(int num1, int num2, int sum)
{
Console.WriteLine("This will add the two together");
sum = num1 + num2;
Console.WriteLine(sum);
return sum;
}
The problem lies here where the compiler does not know which Overall do you mean:
static int Overall(int Num3, int Num4)
{
int Overall;
Console.WriteLine("This will add the two together");
Overall = Overall + iNum3 + iNum4;
Console.WriteLine(Overall);
return overall;
}
make the inner-scoped Overall in small case overall
static int Overall(int Num3, int Num4)
{
int overall;
Console.WriteLine("This will add the two together");
overall= overall + iNum3 + iNum4;
Console.WriteLine(overall);
return Overall;
}
using System;
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(String[] args)
{
int Option;
int Num3, Num4;
Num3=1;
Num4 = 3;
DisplayMenu();
Option = GetUserOption();
while (Option != 0)
{
switch (Option)
{
case 1:
Num1();
break;
case 2:
Num2();
break;
case 3:
Overall(Num3, Num4);
break;
}
}
}
static void DisplayMenu()
{
Console.WriteLine("1. Num1 2.Num2 3.Overall");
}
static int GetUserOption()
{
int Option;
Console.WriteLine("Pick choice");
Option = Convert.ToInt32(Console.ReadLine());
return Option;
}
static int Num1()
{
int Num3;
Console.WriteLine("Enter your first number");
Num3 = Convert.ToInt32(Console.ReadLine());
return Num3;
}
static int Num2()
{
int Num4;
Console.WriteLine("Enter your second number");
Num4 = Convert.ToInt32(Console.ReadLine());
return Num4;
}
public static int Overall(int Num3, int Num4)
{
int Overall=0;
Console.WriteLine("This will add the two together");
Overall = Overall + Num3 + Num4;
Console.WriteLine(Overall);
return Overall;
}
}
}