Accessing values from a method to another method - c#

How do i access values from ReadInput() method so that i can use num1 and num2 for addition in Addition() method
public class HelloWorld
{
public void ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
}
public void Addition()
{
Console.WriteLine("Addition");
ReadInput();
int sum = num1 + num2;
Console.WriteLine("The sum is " + sum);
}
```

Contrary to 3dd's opinion, you should not call Addition method in the ReadInput method, because the ReadInput method, as its name suggests, is only responsible for reading inputs, Also, the Addition method's only task is to perform addition and send the result to the caller so that the caller can use as it wants. and if you call Addition inside ReadInput, you have violated the SRP principle.,
You can optimize your code as follows. Consider the output for the ReadtInput method and the input and output for the Addition method.
you can use tuples or create a separate model, I will write both for you.
with Tuple :
public class HelloWorld
{
public (int number1, int number2) ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
return (num1, num2);
}
public int Addition(int num1, int num2)
{
Console.WriteLine("Addition");
int sum = num1 + num2;
return sum;
}
}
How to use :
internal class Program
{
static void Main(string[] args)
{
HelloWorld helloWorld = new HelloWorld();
var result = helloWorld.ReadInput();
var sumResult = helloWorld.Addition(result.number1, result.number2);
Console.WriteLine("The sum is " + sumResult);
}
}
If you don't want to use tuple, you create a model like below, the changes are as follows :
public class ReadInputModel
{
public int Number1 { get; set; }
public int Number2 { get; set; }
}
And the ReadInput method changes as follows
public ReadInputModel ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
return new ReadInputModel
{
Number1 = num1,
Number2 = num2
};
}
Just pay attention to this point, I only optimized you Code, but still the principles of creating and designing methods are not well followed,for example, you should not do Console.WriteLine in the ReadInput method and its only task should be to read information ,and other things which I think cannot be explained here, it is better to study the principles of Solid well.
I recommend reading these articles:
Solid
SOLID Principles In C#
Csharp best practices dangers of violating solid principles in csharp

public void ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
Addition(num1 , num2);
}
public void Addition(int num1, int num2)
{
Console.WriteLine("Addition");
int sum = num1 + num2;
Console.WriteLine("The sum is " + sum);
}

Related

How to add a second argument(Number) to a calculator program?

I'm working on a small calculator program in Unity.
I only need the calculator to work with two numbers.
The feature I'm trying to implement:
After inputting the math operator, It should display the second number in the third index.
The issue:
Instead of Adding a second number, the first number is being overwritten if a different number is pressed on the keyboard.
Here's the script I've created:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Functions : MonoBehaviour
{
// Global Variable to display text on top panel
public Text panelText;
// Create a number variable
string num;
string num1;
string num2;
string mOpr;
string calNum;
string cbutton;
string opr;
bool isFirstNum;
// Start is called before the first frame update
void Start()
{
}
// A function with an int argument
public void NumberInputOne(string num)
{
num1 = num;
num2 = num;
if (panelText.text.Length < 1)
{
Debug.Log(num1);
panelText.text = num1;
isFirstNum = false;
}
else if (panelText.text.Length > 1 && panelText.text.Length < 3)
{
num2 = num;
Debug.Log(num2);
panelText.text = num1 + mOpr + num2;
}
}
public void OperatorInput(string opr)
{
mOpr = opr;
if (panelText.text.Length > 0 && panelText.text.Length < 2)
{
panelText.text = num1 + mOpr;
}
}
// public void NumberInputTwo(int num)
//{
// ResNum2 = num;
// Debug.Log(ResNum2);
// if (panelText.text.Length > 1 && panelText.text.Length < 3)
// {
// panelText.text = ResNum1 + opr + ResNum2;
// }
// }
public void RestartCal(string cButton)
{
panelText.text = "";
}
}
I've also added a screen recording to capture the issue:
First number being overwritten
Do you have any suggestions?
Thank you
use the NumberInputOne func like below;
public void NumberInputOne(string num)
{
if (num1 is null)
{
Debug.Log(num1);
panelText.text = num1;
num1 = num
}
else
{
num2 = num;
Debug.Log(num2);
panelText.text = num1 + mOpr + num2;
}
}
btw i recommend that you review the sample calculation application codes. because apart from what you're asking, there are places you need to improve in general.
This feels like a beginner programming exercise. But the right way to build a calculator involves programming concepts that you probably haven't been taught yet. Which makes this a poor choice as an assignment.
Personally I would build a calculator by defining a simple syntax tree to represent the formula being input. Including methods to display the formula and calculate the answer. For example;
public interface IValue
{
int Calculate();
string PrintValue();
}
public class Number : IValue
{
public int? Value;
public void AddDigit(int digit) => Value = (Value ?? 0) * 10 + digit;
public int Calculate() => Value ?? 0;
public string PrintValue() => Value?.ToString();
}
public abstract class BinaryOperator : IValue
{
public IValue Left;
public IValue Right;
public abstract int Operation(int left, int right);
public abstract char Operator { get; }
public int Calculate()
{
var left = Left.Calculate();
var right = Right.Calculate();
return Operation(left, right);
}
public string PrintValue() => $"{Left?.PrintValue()} {Operator} {Right?.PrintValue()}";
}
public class Addition : BinaryOperator
{
public override char Operator => '+';
public override int Operation(int left, int right) => left + right;
}
// TODO define other operators
Then think about how each button should change the syntax tree.
// the entire formula
public IValue Root;
// the number currently being typed
public Number Input;
public void Display() {
panelText.text = Root.PrintValue();
}
// start / clear
public void Start(){
Root = Input = new Number(){
Value = 0
};
Display();
}
public void Plus(){
// left as an exercise for the reader
Display();
}
public void Digit(int digit) {
Input.AddDigit(digit);
Display();
}
public void Calculate() {
// left as an exercise for the reader
Display();
}

How to call a function from another class to main class

I created another class (calculations) and created a function in it which checks if a number is even or odd. I want to call this function in my program class so it can check if variable (result) is even or odd.
I tried to call the method like: CheckEvenOrOdd(result).
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number2 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
// i tried this here but it doesn't work: CheckEvenOrOdd(result)
}
}
class Calculations
{
public static void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}
Because your method is in a different class, you're going to have to make it static and then call it by class name first then method name. If it's not static you're going to have to instantiate a new instance of that class before being able to access any of its methods.
(btw you're multiplying number2 by number2, changed it for you as well in the codes provided below hehe)
Static:
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number1 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
Calculations.CheckEvenOrOdd(result);
Console.ReadLine();
}
}
public static class Calculations
{
public static void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}
Not Static:
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number1 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
Calculations calc = new Calculations();
calc.CheckEvenOrOdd(result);
Console.ReadLine();
}
}
public class Calculations
{
public void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}

Unit test takes more time to do a subtraction

I was trying Unit Tests by writing simple examples.
Tested code:
public class Operations
{
public static double Subtraction(double number1, double number2)
{
return number1 - number2;
}
public static double Addition(double number1, double number2)
{
return number1 + number2;
}
public static double Division(double number1, double number2)
{
if (number2 != 0)
{
return number1 / number2;
}
else
{
return number1;
}
}
public static double Multiplication(double number1, double number2)
{
return number1 * number2;
}
}
Test Methods:
[TestClass()]
public class OperationsTests
{
[TestMethod()]
public void SubtractionTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Subtraction(number1, number2);
Assert.AreEqual(-10, result);
}
[TestMethod()]
public void SubtractionTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Subtraction(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void SubtractionTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Subtraction(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void AdditionTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Addition(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void AdditionTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Addition(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void AdditionTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Addition(number1, number2);
Assert.AreEqual(20, result);
}
[TestMethod()]
public void DivisionTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Division(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void DivisionTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Division(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void DivisionTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Division(number1, number2);
Assert.AreEqual(1, result);
}
[TestMethod()]
public void MultiplicationTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Multiplication(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void MultiplicationTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Multiplication(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void MultiplicationTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Multiplication(number1, number2);
Assert.AreEqual(100, result);
}
}
Every test is executing without any error but i noticed that SubtractionTest1 took always 7-8-9ms while the others take less than 1ms, can you explain me why?
Tests result:
MSTest will randomise the order that unit tests run in, as this can sometimes expose bugs in timing or shared state.
Which ever test you run first will take longer because it will be the one required to both JIT compile each of your methods and types and if any of those types have static initialisation to perform then this will also trigger.
I had a unit test suite where the first test would always take approximately 0.5s because I was initialising both the dependency injection and mocking frameworks. Every test post initialisation would take approximately 1ms to 2ms. So the behaviour you see here is totally normal.
For performance testing you must average your results and discard your first result to remove intialisation time from them. You should also test your initialisation speed if that is relevant to your application, but it's usually irrelevant for a server that boots once then stays online and ready.

My C# function will not work [duplicate]

This question already has answers here:
C# error: "An object reference is required for the non-static field, method, or property"
(3 answers)
Error: "an object reference is required for the non-static field, method or property..." [duplicate]
(6 answers)
An object reference is required for the non-static field, method, or property
(3 answers)
CS0120 error under vs2010 beta 2 - object reference is required
(2 answers)
Closed 5 years ago.
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.
namespace FunctionPractice
{
class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers: ");
int firstNumber = Convert.ToInt16(Console.ReadLine());
int secondNumber = Convert.ToInt16(Console.ReadLine());
int result = AddNumbers(firstNumber, secondNumber);
Console.WriteLine(result);
}
}
}
Change the method declaration to
public static int AddNumbers(int number1, int number2)
Or create an instance of Program class in main method and then access the add numbers method.
namespace FunctionPractice
{
class Program
{
public int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers: ");
int firstNumber = Convert.ToInt16(Console.ReadLine());
int secondNumber = Convert.ToInt16(Console.ReadLine());
Program program = new Program();
int result = program.AddNumbers(firstNumber, secondNumber);
Console.WriteLine(result);
}
}
}
Si main is static, AddNumbers must be static as well.
Hey your method works fine you just need to make your "AddNumbers" method static. You can't call a non-static method from a static one. Also you may want to add a read line to the end so the program doesn't just shut off once it writes to the screen. Here would be the fixed code.
class Program
{
public static int AddNumbers(int number1, int number2)
{
int result = number1 + number2;
return result;
}
static void Main(string[] args)
{
Console.WriteLine("Enter 2 numbers: ");
int firstNumber = Convert.ToInt16(Console.ReadLine());
int secondNumber = Convert.ToInt16(Console.ReadLine());
int result = AddNumbers(firstNumber, secondNumber);
Console.WriteLine(result);
Console.ReadLine();
}
}
Make your function as
public static int AddNumbers(int number1, int number2).
This is because, you are calling your function from a static function which belongs to the class itself. Your function belongs to the objects of the class. So when you call static function main(), it doesn't know of which instance's AddNumbers to call. Hence the error. Please read more about static keyword.

METHOD concept program in c# is not working

using System;
class Methodcalling
{
public int Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
static void Main(string[] args)
{
int a, b;
Methodcalling m = new Methodcalling();
Console.WriteLine("enter a no.:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter a no.:");
b = Convert.ToInt32(Console.ReadLine());
int result = m.Values(a, b);
}
}
ERROR:'Methodcalling.Values(int, int)': not all code paths return a value
In this way its showing error in VISUAL STUDIO 2013.
This error is because you have declared the function to return an int, but your function does not return anything.
Have a look at this link here for a reference on the function declaration in c#.
For a relief from the error, try adding return 0; to the end of the function.
public int Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
return 0; // Return zero to the calling function.
}
Now you could call this function like this to capture the return value.
int TheReturnValue = Values(num1 , num2); //You will get 0 as value for TheReturnValue variable.
or change the int to void as in public void Values(int num1, int num2) if you don't want to return any values.
here is the usage:
public void Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
and you could call the function(void Return Type) like this:
m.Values(a, b); //without assigning it to a variable
Since you are only writing to console using this function, void datatype would be the better option.
I hope this helps.
You have to return an int value from the method as the method's signature defines a return type of int, and you are also calling
int result = m.Values(a, b);
which suggest that the method would return an integer but you have no return statement in your method.
You can modify the method like this if you don't want any integer to be returned.
using System;
class Methodcalling {
public void Values(int num1, int num2) {
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
static void Main(string[] args) {
int a, b;
Methodcalling m = new Methodcalling();
Console.WriteLine("enter a no.:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter a no.:");
b = Convert.ToInt32(Console.ReadLine());
m.Values(a, b);
}
}

Categories

Resources