I am struggling to understand how functions work outside of main. I simply need to compute a total using information that is put in by the user in main, but I am supposed to call on a function to total this up. Here is the code I have so far, I am sure it is not very close to right, a nudge in the right direction would be a huge help
namespace ConsoleApplication17
{
class Program
{
static void Main(string[] args)
{
string customerName, customerState;
double numberItems, itemPrice;
Console.WriteLine("Please enter the customer name");
customerName = Console.ReadLine();
Console.WriteLine("Please enter the state in which you reside:");
customerState = Console.ReadLine();
Console.WriteLine("How many items were purchased?");
numberItems = int.Parse(Console.ReadLine());
Console.WriteLine("What was the price of said items?");
itemPrice = Convert.ToDouble(Console.ReadLine());
}
public static double ComputeTotal (double total)
{
double totalAmount;
Console.Write(total);
}
}
public static double ComputeTax (double totalAmount, string state, string fl, string nj, string ny)
{
if (state == fl)
return totalAmount*.06;
else if (state == nj)
return totalAmount*.07;
else if (state == ny)
return totalAmount*.04;
}
In short, I need to use the function ComputeTotal to multiply the numberItems and itemPrice
A function basically takes some data from you and returns (some other?) data to you.
In your case you want to give the function 2 pieces of data - qty and price, and you want it to return you the total price.
public static double ComputeTotal(double qty, double price)
{
return qty* price;
}
This function ComputeTotal accepts 2 variables of type double.
They are qty and price.
The function then multiplies these 2 variables and returns the result to the caller.
In your main method, this is how you use(call) the function.
static void Main(string[] args)
{
// rest of your code here
var total = ComputeTotal(numberItems, itemPrice);
Console.WriteLine(total);
}
Here I am creating a new variable called total, and I am assigning the return value of ComputeTotal function to this variable.
The ComputeTotal function requires 2 parameters and I am passing 2 variables that you created in your code. For brevity I have not typed any of your original code, and your code should be at the location of my comment "// rest of your code here" .
your method/function could be like this
public static double ComputeTotal (double itemPrice, int quantity)
{
return itemPrice * quantity
}
in your main method you can do like this
static void Main(string[] args)
{
double total_price=0.0;
total_price = ComputeTotal ( itemPrice, numberItems)
Console.WriteLine("totl price : {0}",total_price);
}
understand how functions work
I am distilling this significantly, but a function for this definition is really a method which returns a value. In C# there is no distinction between functions and methods for they are the same with differences being whether something returns data or operates on a referenced instance of a class instance.
The real difference is in the calling mechanism on whether one instantiates (calls new on a class); they are instantiatitng a class. For this assignment, your teacher does not want you to instantiate a class.
Hence you will call function(s) which are static methods that can be called by anyone without instantiating any classes.
With that in mind, your teacher wants you to learn a function type call so he /she wants you to create a static method off of the class Program which can be called by Main because it is static as well.
So create your function type static method that will return a value; hence it will mimic functions in other languages.
outside of main.
Now Main can have static methods, but so can other classes which can be called from within a Main's static method as well.
The other class like that looks like this...and is called by fully qualifying the location such as {ClassName}.{Static Method Name}.
class Program {
static void Main(...)
{
Console.WriteLine( TheOtherClass.AFunction() );
}
}
public class TheOtherClass
{
public static string AFunction()
{
return "A String From this Function. :-) ";
}
}
Note if TheOtherClass is in a different namespace, access it such as {Namespace}.{ClassName}.{Static Method Name}. But you should make sure that the other class is in the same Namespace as found in your current example of ConsoleApplication17.
Related
Very, very new programmer here facing some big troubles, I am trying to achieve as follows:
I want to write a very basic program in which the user is prompted to input two double variables, I then want the program to call separate methods, that will perform mathematical operations on those two variables and provide the user the answers.
Example of desired output:
Input First Number
x
Input Second Number
y
Add: z
Subtract: z
My aim in this is to practice using objects, but I am having issues, see this snippet as an example.
class Variables
{
public string First { get; set; }
public string Second { get; set; }
}
class Program
{
Variables inputs = new Variables()
{
Console.WriteLine("Please input first number"),
First = Console.ReadLine(),
Console.WriteLine("Please input second number"),
Second = Console.ReadLine(),
};
static void Main(string[] args)
{
Addthem();
}
public string Addthem()
{
double answer = Convert.ToDouble(inputs.First) + Convert.ToDouble(inputs.Second);
return ("Added: " + answer);
}
}
When trying to call Addthem, I have no 'object reference',
in my object 'inputs', I cannot print to console to prompt user input?
And finally (most mind bogglingly to me), my Main method is not suitable as an entry point for the program, this is what I am MOST clueless on.
Am I even on the right track? As I said very novice so sorry for egregious errors or general ignorance, I am just trying to better understand what I am not seeing in the interactions between Classes, Objects, Methods.
You've got all the ingredients right, but they need to be rearranged to make a good cake. Main() is the entry point, so anything you want to do has to be inside Main() or be called by something inside Main().
A useful concept to know is the difference between a class and an object.
A class is just a specification which says you can have these properties and methods, but you need to create an instance of the class first.
An object is an "instance" of a class and you can call the class methods (functions) through that object. Eg inputs is an instance of the Variables class.
using System;
class Variables
{
public string First { get; set; }
public string Second { get; set; }
public string AddthemInClass()
{
double answer = Convert.ToDouble(First) + Convert.ToDouble(Second);
return ("Added: " + answer);
}
}
class Program
{
static void Main(string[] args)
{
// You had the code to initialise `inputs` outside of Main(),
// so it wouldn't get executed
// It needs to be inside Main()
// `inputs` is created as an instance of the `Variables` class
Variables inputs = new Variables();
Console.WriteLine("Please input first number");
inputs.First = Console.ReadLine();
Console.WriteLine("Please input second number");
inputs.Second = Console.ReadLine();
// You need to tell Addthem() what to work on, ie, pass in `inputs`
var result = Addthem(inputs);
Console.WriteLine( result );
// Or, you could call AddthemInClass through the `inputs` object
// because AddthemInClass is a method of Variables class
var result2 = inputs.AddthemInClass();
Console.WriteLine( result2 );
}
// This should be a static method. If you don't do this, you need to have it
// in a class and call it through an instance of that class
// You could put it inside Variables class - see AddThemInClass()
public static string Addthem(Variables inputs)
{
double answer = Convert.ToDouble(inputs.First) + Convert.ToDouble(inputs.Second);
return ("Added: " + answer);
}
}
So I have the method that makes the factorial of a number but I don't want to make it every time I need it. I want to make it global so I can call it everytime I need it.
double factorial(int i)
{
int input = i;
double result = 1;
if (i == 0)
{
result = 1;
return result;
}
else
{
while (input != 1)
{
result = result * input;
input = input - 1;
}
return result;
}
}
What is does is that if gives you the factorial of a number in my Windows Form but I use it in all my windows forms so I copy this method in each class.
p = factorial(i))
That's how I call it and it works perfectly but is there a way to make it it's own class so I don't have to copy it to every one of my windows Forms and if so how would I call it?
I copy this method in each class. Is there a way to make it it's own class?
Absolutely! Since your method does not depend on fields of your class, make it static, and add it to a class that hosts math helper methods, for example
public static class MathHelpers {
public static double Factorial(int i) {
...
}
}
Note that I also marked the class static to ensure its users that they never need to create an instance of it. Essentially, such class becomes a holder of static methods.
You call the method from your form as follows:
double f = MathHelpers.Factorial(5);
Generally you can add this to a class and make the method public static.
I have a basic class with this method including
public class Account
{
//MEMBERS
private int acctNo;
protected double balance;
public double deposit;
// CONSTRUCTORS
public Account() //member intitilization
{
acctNo = 54534190;
balance = 7500;
deposit= 1500;
}
//PROPERTIES
public int AcctNo
{
get {return acctNo; }
set {acctNo = value; }
}
public double Balance
{
get { return balance; }
set { balance = value; }
}
public double Deposit
{
get {return deposit; }
set {deposit = value; }
}
public virtual double getDeposit (double amount)
{
double transactionAmt=0.00;
if (amount>0)
{
balance+=amount;
transactionAmt= amount;
}
return transactionAmt;
}
Now in my actual program I am trying to output this method. What would my writeline look like?
I tried to write this:
static void Main(string[] args)
{
Console.WriteLine("CREATING ACCOUNT");
Account myAcctDefault = new Account();
DumpContents(myAcctDefault);
Pause();
}
static void DumpContents(Account account)
{
Console.WriteLine(" output {0}", account.getDeposit());
}
I am getting an error saying:
no overload for method 'getDeposit' takes 0 arguments.
What am I doing wrong, am I trying to output this method incorrect?
Any help, insight or suggestions would be extremely helpful.
I am new to c# as I'm sure you can tell. What is the proper process to output a method in this context?
I am getting an error saying "no overload for method 'getDeposit' takes 0 arguments". What am I doing wrong
Exactly what it says. Here's your method call:
Console.WriteLine(" output {0}", account.getDeposit());
... and here's the method declaration:
public virtual double getDeposit (double amount)
Note how the method declares a parameter - but you're not providing an argument. Either you need to get rid of the parameter, or you need to add an argument to the method call. Or you need to change to using a different method - one which doesn't change the balance of the account. (It seems unlikely that you want to do that in this case.) Perhaps you should add a Balance property:
// Please note that this should probably be decimal - see below
public double Balance { get { return balance; } }
Then call it with:
Console.WriteLine(" output {0}", account.Balance);
Additionally:
For financial quantities, it's generally better to use decimal than double. Read my articles on decimal floating point and binary floating point for more information.
Your getDeposit method doesn't follow .NET naming conventions, where (at least public) methods are named in PascalCase, with a leading capital letter
Your getDeposit method is oddly named as it isn't "getting" a deposit - it's making a deposit (and returning the balance)
Your getDeposit method always returns the value passed into it, unless it's negative. That seems odd to me - if it's going to return anything, shouldn't it return the balance?
Your getDeposit method silently ignores negative deposits. I'd expect this to throw an error, as trying to make a negative deposit indicates a programming error IMO.
Your getDeposit method takes one argument that you are not passing to it. Depends what you want to achieve either pass a value to method:
static void DumpContents(Account account)
{
double deposit = 1000;
Console.WriteLine(" output {0}", account.getDeposit(deposit));
}
or remove this argumentparameter from the method signature.
//You have to pass a double value into the method, because there is only one method
//and wants a double paramater:
//this is what you created:
public double getDeposit(double amount) // <-
{
double transactionAmt = 0.00;
if (amount > 0)
{
balance += amount;
transactionAmt = amount;
}
return transactionAmt;
}
//This how you should call it:
static void DumpContents(Account account)
{
Console.WriteLine(" output {0}", account.getDeposit(34.90)); //<-
}
I Want to call a class into the Main method.. And I'm getting this error :s
Code:
using System;
namespace AddMinusDivideMultiply
{
class Program
{
public static int i, j;
public static void Main()
{
Console.Write("Please Enter The First Number :");
string temp = Console.ReadLine();
i = Int32.Parse(temp);
Console.Write("Please Enter The Second Number :");
temp = Console.ReadLine();
j = Int32.Parse(temp);
Minuz.minus(); // Here its generating an Error - Error 1 The name 'Minuz' does not exist in the current context
}
}
class Terms
{
public static void Add()
{
int add;
add = Program.i + Program.j;
Console.WriteLine("The Addition Of The First and The Second Number is {0}", add);
}
class Minuz
{
public static void Minus()
{
int minus;
minus = Program.i - Program.j;
Console.WriteLine("The Subraction Of The First and The Second Number is {0}", minus);
}
}
}
}
Case matters in C#!
Call this:
Minuz.Minus();
Also, need to change your braces so it's not inside Terms:
class Terms
{
public static void Add()
{
int add;
add = Program.i + Program.j;
Console.WriteLine("The Addition Of The First and The Second Number is {0}", add);
}
}
class Minuz
{
public static void Minus()
{
int minus;
minus = Program.i - Program.j;
Console.WriteLine("The Subraction Of The First and The Second Number is {0}", minus);
}
}
That's because the Class Minuz is defined inside the Class Terms so it really is not defined in the context you are trying to use it.
You did not close the definition of Terms before declaring Minuz
The problem is that the class Minuz is declared inside the class Terms, and it is private. This means that it is not visible from the Main method.
There are two possible ways to solve it:
Make the class Minuz internal or public and chance the call to the Minus method to Terms.Minuz.Minus()
Move the declaration of the class Minuz out from the Terms class so that it is instead declared in the namespace.
Also, as pointed out by others; mind the case of the method name. That will be your next problem once the class visibility has been fixed.
You have embedded the Minuz class inside the Terms class. If you make it public class Minuz you can call
Terms.Minuz.Minus();
to solve the error. But you probably want to move the Minuz class out of Terms.
Unless its a typo, you're missing a closing bracket for the Terms class. The way its currently written in your post, you would need to put this statement in your Main method:
Terms.Minuz.Minus();
I have 3 classes named maths, alphabets and main. The Maths Class contains Add function and alphabet class contains a function same as Maths class. But the third class is for calling the function which is used for calling the above functions defined in the above classes.
How it will work?
If the functions are static you'll have to explicitly tell which class they belong to - the compiler will be unable to resolve otherwise:
Maths.Add();
If they are not static the compiler will determine this based on the object type:
Maths maths = new Maths();
maths.Add(); // the necessary class and function will be resolved automatically
Is this what you mean?
public class Maths
{
public Maths() { }
public Double Add(Double numberOne, Double numberTwo)
{
return numberOne + numberTwo;
}
}
public class Alphabet
{
public Alaphabet() { }
public String Add(Char characterOne, Char characterTwo)
{
return characterOne.ToString() + characterTwo.ToString();
}
}
public void Main()
{
Alphabet alaphatbet = new Alphabet();
String alphaAdd = alphabet.Add('a', 'b'); // Gives "ab"
Maths maths = new Maths();
Double mathsAdd = maths.Add(10, 5); // Gives 15
}
By using an interface that defines an Add function and having Math and alphabets implement that interface.
C# programs do not contain "functions", but instead methods, which are attached to classes. So you call Math.Add or Alphabet.Add. Conflicting function names do not exist, in C#, for that reason. Conflicting class names are resolved by name spaces.