How to call a function from another class to main class - c#

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 ");
}
}
}

Related

How to restart a script if a string is equal to Y or y?

public class Program
{
public static void Main()
{
{
string value;
do
{
Console.WriteLine("First value to add? : ");
int a1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Second value to add? : ");
int a2 = Convert.ToInt32(Console.ReadLine());
Console.Write(a1+a2);
Console.WriteLine("Type Y or y to restart the program.");
value = Console.ReadLine();
}
while (value == "Y" || "y");
}
}
}
I get this error:
source.cs(1,1): error CS1022: Type or namespace definition, or end-of-file expected. I think that the script cant access the string but idk.
I expected that the script would restart

Accessing values from a method to another method

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);
}

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);
}
}

Else...If statements not returning methods equations back properly in C#?

I'm banging my head trying to figure out why I can't get my equations to not return as Zero as it seems that for some reason the MathOperations methods aren't doing there job? If anyone could help I would much appreciate it. Thanks in advance!
class MathUI
{
public void PromptForInt()
{
MathOperations ops = new MathOperations();
Console.WriteLine("Enter first number to calculate");
ops.Operand1 = int.Parse(Console.ReadLine());
Console.WriteLine("\nEnter second number to calculate");
ops.Operand2 = int.Parse(Console.ReadLine());
return;
}
public void PromptForChoice()
{
int choice;
MathOperations result = new MathOperations();
Console.WriteLine("\nWhat type of operation would you like to perform?");
Console.WriteLine("[1] Add \n[2] Subtract \n[3] Multiply \n[4] Divide \n[5] Exit \n");
Console.Write("Enter your choice: ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
Console.WriteLine(result.AddNumbers());
}
else if (choice == 2)
{
Console.WriteLine(result.SubtractNumbers());
}
else if (choice == 3)
{
Console.WriteLine(result.MultiplyNumbers());
}
else if (choice == 4)
{
Console.WriteLine(result.DivideNumbers());
}
else if (choice == 5)
{
Environment.Exit(0);
}
else
{
Console.WriteLine("\nInvalid input entered!");
}
}
class MathOperations
{
private int operand1;
private int operand2;
public int Operand1
{
get
{
return operand1;
}
set
{
operand1 = value;
}
}
public int Operand2
{
get
{
return operand2;
}
set
{
operand2 = value;
}
}
public MathOperations()
{
operand1 = 0;
operand2 = 0;
}
public int AddNumbers()
{
return operand1 + operand2;
}
public int SubtractNumbers()
{
return operand1 - operand2;
}
public float DivideNumbers()
{
return (float)operand1 / (float)operand2; // (float) used to show output with decimal point
}
public int MultiplyNumbers()
{
return operand1 * operand2;
}
You are setting values for operand1 and operand2 for ops object but not result object.
MathOperations ops = new MathOperations();
Console.WriteLine("Enter first number to calculate");
ops.Operand1 = int.Parse(Console.ReadLine());
Console.WriteLine("\nEnter second number to calculate");
ops.Operand2 = int.Parse(Console.ReadLine());
but calling methods on result object whose operand1 and operand2 are initialized to 0 and hence the return values of functions. Remember ops' operand1 and operand2 hold user's input, not result's operand1 and operand2. You should use same ops object for result calculation.

Using multiple classes

I am trying to make a simple program that asks the user to enter an integer. Once the program receives the input it takes and stores it and then counts from 1 to the input integer and sums the total of the count. Then it displays the results in a meaningful way to the user and prompts them if they would like to process another number. The point of this program is to use loops and multiple classes. I know that I am really close to the desired end product but cannot figure out why the AccumulateValue() method is not working properly. It does not seem to be going into the conditional while statement that I made. If anyone could give me some insight to my problem that would be great!
Here is my code:
AccumulatorApp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class AccumulatorApp
{
static void Main(string[] args)
{
string loopControl = "Y";
int sum;
int enteredValue;
DisplayTitle();
while (loopControl == "Y" || loopControl == "YES")
{
enteredValue = InputInteger(0);
Accumulator number = new Accumulator(enteredValue);
sum = number.AccumulateValues();
DisplayOutput(sum, enteredValue);
Console.Write("\tWould you like to process another number? \n\t\t<Y or N>: ");
loopControl = Console.ReadLine().ToUpper();
}
}
public static void DisplayTitle()
{
Console.BackgroundColor = ConsoleColor.White;
Console.ForegroundColor = ConsoleColor.Black;
Console.Clear();
Console.WriteLine();
Console.WriteLine("\tProgramming Assignment 05 - Accumulator - Robert");
DrawLine();
}
public static int InputInteger(int enteredValue)
{
Console.Write("\tPlease enter a positive integer: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
if (enteredValue > 0)
{
return enteredValue;
}
else
{
Console.WriteLine("\tInvalid input. Please enter a POSITIVE integer: ");
enteredValue = Convert.ToInt32(Console.ReadLine());
}
return enteredValue;
/*
Console.Write("Please enter a positive integer: ");
int enteredValue = Convert.ToInt32(Console.ReadLine());
return enteredValue;
* */
}
public static void DisplayOutput(int sum, int inputValue)
{
Console.WriteLine("\tThe inputed integer is: {0}", inputValue);
Console.WriteLine("\tThe sum of 1 through {0} = {1}", inputValue, sum);
DrawLine();
}
public static void DrawLine()
{
Console.WriteLine("\t______________________________________________________");
Console.WriteLine();
}
}
}
Accumulator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Accumulator
{
int integerEntered;
public Accumulator()
{
}
public Accumulator(int integerEntered)
{
int enteredInteger = integerEntered;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
int counterValue = 1;
while (counterValue <= integerEntered)
{
Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
accumulatedValue = accumulatedValue + counterValue;
counterValue = counterValue + 1;
}
return accumulatedValue;
}
}
}
When you are instantiating a new instance of Accumulator through it's constructor containing one int argument you were setting the passed value equal to the field within the class (Setting them both to 0.)
Your accumulator class should look like this:
class Accumulator
{
int integerEntered;
public Accumulator()
{
}
public Accumulator(int passedInteger)
{
//Local field is equal to passedInteger, not the other way around.
integerEntered = passedInteger;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
int counterValue = 1;
while (counterValue <= integerEntered)
{
Console.WriteLine("\tPasses through loop = {0}", accumulatedValue);
accumulatedValue = accumulatedValue + counterValue;
//Increment does the same thing you were doing
counterValue++;
}
return accumulatedValue;
}
}
It looks like the problem may actually be with your value constructor. When this line is called:
Accumulator number = new Accumulator(enteredValue);
A new Accumulator is being made with your value constructor:
public Accumulator(int integerEntered)
{
int enteredInteger = integerEntered;
}
The problem is that integerEntered isn't really saved anywhere and once enteredInteger goes out of scope (end of constructor), the value that was entered is essentially lost as far as the Accumulator object is concerned. I think what you want is:
public Accumulator(int integerEntered)
{
integerEntered = integerEntered;
}
As a heads up, you may have to do this.integerEntered = integerEntered;
Also I think you want to subtract 1 from integerEntered each iteration of your while loop in AccumulateValues().
There 2 -3 things needs to be changed
1) you are not assigning values to integerEntered in your constructor so I have changed it
2) you should integerEntered as a property so i have changed it to public int integerEntered { get; set; }
3) the logic of calculating to count AccumulateValues .. actually mathematical formula is the sum up to integer n is = (n * (n+1))/2 so i have changed it too
try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project
{
class Accumulator
{
public int integerEntered { get; set; }
public Accumulator()
{
}
public Accumulator(int integerPassed)
{
integerEntered = integerPassed;
}
public int AccumulateValues()
{
int accumulatedValue = 0;
if(integerEntered > 0)
{
accumulatedValue = (integerEntered * (integerEntered + 1))/2;
}
return accumulatedValue;
}
}
}

Categories

Resources