METHOD concept program in c# is not working - c#

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

Related

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

Problem with variables while trying to make a c# library(.dll)

I want to make a library that sums 2 numbers(a and b) and then stores the value into a result variable inside a library(.dll).
I tried this:
public static void Sum(int number1, int number2, int result)
{
result = number1 + number2;
}
but I can't make it so that in a program that uses this library, you can get the value of the result value that this function calculates and that's what I couldn't figure out for the past days. If you need any more info I will gladly provide it to you! Hope someone can help me!
In your case you do not return any result, consider using some of the following:
public static void Main()
{
var sumRes = SumResut(1, 2);
Console.WriteLine($"SumResult = {sumRes}");
OutSum(1, 2, out int outRes);
Console.WriteLine($"OutSum = {outRes}");
int refRes = 0;
RefSum(1, 2, ref refRes);
Console.WriteLine($"RefSum = {refRes}");
}
public static int SumResut(int number1, int number2)
{
return number1 + number2;
}
public static void OutSum(int number1, int number2, out int result)
{
result = number1 + number2;
}
public static void RefSum(int number1, int number2, ref int result)
{
result = number1 + number2;
}

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

Call value from a method inside Main() function

I am trying to call a value from a method called GetInputstring from inside Main() method, and proceed to the next steps.
I am stuck regards to how I could get the value myInt and move along.
myInt (where it has two * around) inside Main() is where it gets the errors.
static void Main(string[] args)
{
GetInputstring(**myInt**);
if (**myInt** <= 0)
{
Write1(**myInt**);
}
else
{
Write2(**myInt**);
}
Console.ReadKey();
}
public int GetInputstring(int myInt)
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
myInt = Int32.Parse(myInput);
return myInt;
}
static void Write1(int myInt)
{
while (myInt <= 0)
{
Console.WriteLine("{0}", myInt++);
}
}
static void Write2(int myInt)
{
while (myInt >= 0)
{
Console.WriteLine("{0}", myInt--);
}
}
MyInt is your parameter(the value you pass to your method) and it's not initialized. Further you don't catch your return value (which should be myInt)
You also need to make your methods static in order to call them from a static method or you create an instance of the class and invoke the method on it
That's how you'll get what you want:
static void Main(string[] args)
{
int myInt = GetInputstring(); //MyInt gets set with your return value
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring() //Deleted parameter because you don't need it.
{
string myInput;
//int myInt;
Console.Write("Please enter a number: ");
myInput = Console.ReadLine();
int myInt = Int32.Parse(myInput);
return myInt;
}
You need to initialize your myInt variable and store it in the local or global scope. With this variable you will need to set it with the value you get from GetInputString() because you are not passing the int as a ref it will not be assigned in the method. You also need to make your methods static so they can be called from Main without creating an instance, Ex: public static int GetInputstring()
int myInt = 0;
myInt = GetInputstring(myInt);
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
Alternatively (And preferably), you could make GetInputString() assign the value because it dosen't need myInt to be passed as an parameter.
static void Main(string[] args)
{
int myInt = GetInputstring();
if (myInt <= 0)
{
Write1(myInt);
}
else
{
Write2(myInt);
}
Console.ReadKey();
}
public static int GetInputstring()
{
Console.Write("Please enter a number: ");
string myInput = Console.ReadLine();
return Int32.Parse(myInput);
}

Categories

Resources