Here is our example from class with extensive comments
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace methodsExample { class Program { /********************* * the point of this excercise is to show * how to break a program into methods * we have a display method and seperate * methods to calcualte the gas mileage * and the cost per mile. * the point of breaking a program into methods * is to divide the work and make it easier * to maintain, debug and understand. * Ideally each method should do one thing * that way it is obvious where to look if * something goes wrong * Steve Conger 10/4/2011 */ static void Main(string[] args) { //a static method is loaded automatically //into RAM, but the rest of the class is not //so we need to "instantiate" the class //to load it into memory where it can be used Program p = new Program(); p.Display(); //call the display method p.PauseIt();// call the PauseIT class } //void methods don't return a value //they just do their thing private void Display() { //inputs //just like what we did in the first assignment Console.WriteLine("Enter the Mileage"); double mileage = double.Parse(Console.ReadLine()); Console.WriteLine("Enter The Gallons"); double gals = double.Parse(Console.ReadLine()); Console.WriteLine("Enter The price per gallon"); double price = double.Parse(Console.ReadLine()); //outputs Console.WriteLine("Your miles per gallon is {0:F2}", CalculateGasMileage(mileage, gals));//calls the CalculateGasMileage //as part of the write line. You can only do this if the //method returns a value //this is another way to do it //here we assign the returned result of the method //to a new variable double mpg=CalculateGasMileage(mileage, gals); //we can use that variable in the writeline instead of calling //the method again Console.WriteLine("Your cost per mile is {0:C}", CalculateCostPerMile(mpg,price)); } //this method returns a double //it takes two parameters that are give values //when the method is called in the Display() method above private double CalculateGasMileage(double miles, double gallons) { double milesPerGallon; milesPerGallon = miles / gallons; return milesPerGallon; } private double CalculateCostPerMile(double milesPerGal, double pricePerGallon) { //double costPerGallon=0; //this is a different way to return a value //you can return the equation directly return pricePerGallon / milesPerGal; } private void PauseIt() { Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } }
No comments:
Post a Comment