How to assign variable to the result of a method in C# - c#

I'm new to the concept of methods in C#, and I am trying to wrap my head around solving this problem that uses methods to calculate compound interest. I am having a couple problems with the code itself, but the main concept I am struggling with is how to return the variable "double finalAmount" through the use of my methods CalculateCompoundInterest (both variations). Here is my code so far:
using System;
namespace CompoundInterestCalculator
{
public class CompoundCalculator
{
const int EXIT = 0;
const int CALCULATE_DAILY = 1;
const int CALCULATE_QUARTERLY = 2;
const int CALCULATE_VARIABLE = 3;
const int NUM_OPTIONS = 3;
public static void Main()
{
int menuOption;
WelcomeMessage();
do
{
DisplayMenu();
menuOption = ReadOption();
if (menuOption != EXIT)
{
double finalAmount = CalculateInterest(menuOption);
OutputResult(finalAmount);
}
} while (menuOption != EXIT);
ExitProgram();
} // end Main
// Fill in the appropriate modifier and return type (_ _) in the method declaration
public static void WelcomeMessage()
{
Console.WriteLine("\n\n\tCompound Interest Calculator\n");
} // end WelcomeMessage
// Fill in the appropriate modifier and return type (_ _) in the method declaration
public static void ExitProgram()
{
Console.Write("\n\nPress enter to exit.");
Console.ReadLine();
} // end ExitProgram
static void DisplayMenu()
{
string menu = "\n\n1) Calculate final amount after interest (compounded daily)"
+ "\n2) Calculate final amount after interest (compounded quarterly)"
+ "\n3) Calculate final amount after interest (define number of times compounded yearly)"
+ "\n\nEnter your option(1-3 or 0 to exit): ";
Console.Write(menu);
} // end DisplayMenu
public static void OutputResult(double finalAmount)
{
// Display the message "The final amount of money plus interest is: $(amount)"
// The amount should display as currency, with two decimal places, e.g. $10,000.00
Console.WriteLine("The final amount of money plus interest is: ${0.2}", finalAmount);
} // end OutputResult
static int ReadOption()
{
string choice;
int option;
bool okayChoice;
do
{
choice = Console.ReadLine();
okayChoice = int.TryParse(choice, out option);
if (!okayChoice || option < 0 || option > NUM_OPTIONS)
{
okayChoice = false;
Console.WriteLine("You did not enter a correct option.\n\n Please try again");
DisplayMenu();
}
} while (!okayChoice);
return option;
} // end ReadOption
public static double CalculateInterest(int menuOption)
{
// (For this exercise, we will assume the user is inputting correct input.)
double principal;
double interestRate;
int numYears;
double finalAmount;
Console.Write("Enter the principal amount: ");
principal = Double.Parse(Console.ReadLine());
Console.Write("Enter the interest rate: ");
interestRate = Double.Parse(Console.ReadLine());
Console.Write("Enter the number of years that interest is accumulated for: ");
numYears = Int32.Parse(Console.ReadLine());
if (menuOption == CALCULATE_DAILY || menuOption == CALCULATE_QUARTERLY)
{
if (menuOption == CALCULATE_DAILY)
{
// Call the appropriate CalculateCompoundInterest method
CalculateCompoundInterest( principal, interestRate, numYears);
}
else
{
// Call the appropriate CalculateCompoundInterest method
CalculateCompoundInterest( principal, interestRate, numYears, 4);
}
}
else
{
Console.Write("Enter the number of times the interest is compounded yearly: ");
int numTimesCompounded = Int32.Parse(Console.ReadLine());
// Call the appropriate CalculateCompoundInterest method
CalculateCompoundInterest( principal, interestRate, numYears, numTimesCompounded);
}
Console.WriteLine();
// return the amount calculated by the compound interest method
return finalAmount;
} // End CalculateInterest
// Declare and implement the method CalculateCompoundInterest whose parameters are the principal, interest rate, and number of years (in that order)- make sure it is public!
// For the declaration select an appropriate modifier, return type, and types for the parameters
// This version assumes the interest is compounded daily (365 times a year)
// For both methods, you should assume the interest rate is input already in decimal form (i.e. 0.02 rather than 2 for a 2% rate)
public static double CalculateCompoundInterest(double principal, double interestRate, int numYears )
{
double compoundInterest;
compoundInterest = principal * Math.Pow(1 + interestRate / numYears, 1);
return compoundInterest;
}
// Declare and implement the method CalculateCompoundInterest whose parameters are the principal, interest rate, number of years, and number of times compounded yearly - make sure it is public!
// For the declaration select an appropriate modifier, return type, and types for the parameters
// This version allows the number of times compounded yearly to be specified.
public static double CalculateCompoundInterest(double principal, double interestRate, int numYears, int numTimesCompounded)
{
double compoundInterest;
compoundInterest = principal * Math.Pow(1 + interestRate / numYears, numTimesCompounded);
return compoundInterest;
}
}//end class
}//end namespace
Basically I am trying to figure out how to obtain results from methods, and how to use them in other methods (e.g. for value/parameter arithmetic). Feel free to let me know if you think there is something else that is wrong with the purpose of the program (to calculate compound interest). Also let me know if this is inappropriate for Stack Overflow, I am new to the website. Thanks guys.

I 'think' this is what you are looking for
var interest = CalculateCompoundInterest( principal, interestRate, numYears, 4);
edit
Additionally you may want to refactor the following 2 methods into 1 method. Hint - optional parameters
public static double CalculateCompoundInterest(double principal, double interestRate, int numYears )
{
double compoundInterest;
compoundInterest = principal * Math.Pow(1 + interestRate / numYears, 1);
return compoundInterest;
}
public static double CalculateCompoundInterest(double principal, double interestRate, int numYears, int numTimesCompounded)
{
double compoundInterest;
compoundInterest = principal * Math.Pow(1 + interestRate / numYears, numTimesCompounded);
return compoundInterest;
}
}

Related

Any way to clean up my code for a simple console calculator?

Is there any way for me to clean this code up for it to be more efficient? Also, could someone point me into the direction of making this app more advanced than what I have done?
As I am progressing with C# and starting to understand more about what certain things do I am lost as to how to implement my knowledge into actual code.
Any starting points for creating applications to help me remember how to and when to use certain code, for example: Encapsulation, interface polymorphism etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNetCalculator
{public class Calculator
{
// User Input1
public int number1;
// User Input2
public int number2;
// User Input3
public int number3;
//User Input4
public char YesOrNo;
// Input1 property
public int Input1 { get
{
return number1;
} set {
number1 = value;
}
}
// Input2 property
public int Input2 { get
{
return number2;
} set {
number2 = value;
}
}
// Input3 property
public int Input3
{
get
{
return number3;
}
set {
number3 = value;
}
}
// Input4 property
public char Input4
{
get
{
return YesOrNo;
}
set
{
YesOrNo = value;
}
}
//Addition
public void Addition(int number1, int number2)
{
Console.WriteLine("\nAddition of the 2 Numbers is " + (number1 + number2));
}
//Subtraction
public void Subtraction(int number1, int number2)
{
Console.WriteLine("Subtraction of the 2 Numbers is: " + (number1 - number2));
}
//Division
public void Division(int number1, int number2)
{
Console.WriteLine("Division of the 2 Numbers is: " + (number1 / number2));
}
//Multiplication
public void Multiplication(int number1, int number2)
{
Console.WriteLine("Multiplication of the 2 Numbers is: " + (number1 * number2));
}
}
class Program
{
static void Main(string[] args)
{
Calculator calc = new Calculator();
//Start of the application
Start:
Console.WriteLine("\nCalculation of the 2 numbers using 4 different operations");
//User input with the first number
Console.Write("\nEnter The first number: ");
calc.Input1 = Convert.ToInt16(Console.ReadLine());
//User input with the second number
Console.Write("Enter the second number: ");
calc.Input2 = Convert.ToInt16(Console.ReadLine());
//User input which is equal to 1 of the 4 math operations
Console.Write("Press 1 for Addition, Press 2 for Subtraction, Press 3 for Division or Press 4 for Multiplication: ");
calc.number3 = Convert.ToInt16(Console.ReadLine());
// if the user input is 1 then call the addition operation
if (calc.number3 == 1)
{
//call addition
calc.Addition(calc.number1, calc.number2);
}
else
// if the user input is 2 then call the subtraction operation
if (calc.number3 == 2)
{
//call subtraction
calc.Subtraction(calc.number1, calc.number2);
}
else
// if the user input is 3 then call the division operation
if (calc.number3 == 3)
{
//call division
calc.Division(calc.number1, calc.number2);
}
else
// if the user input is 4 then call the multiplication operation
if (calc.number3 == 4)
{
//call multiplication
calc.Multiplication(calc.number1, calc.number2);
}
//User input for starting again or finishing the application
Console.Write("\nWould you like to start again? Y or N: ");
calc.YesOrNo = Convert.ToChar(Console.ReadLine());
//if the user input is equal to Y then send them back to the start of the application
if (calc.YesOrNo == 'Y')
{
goto Start;
}
else
// if the user input is equal to N then send them to the end of the application
if (calc.YesOrNo == 'N')
{
goto End;
}
//End of the application
End:
//Exit
Console.WriteLine("\nPress Enter to exit!");
Console.Read();
}
}
}
My comments:
In your Calculator class, you should not put variable that are not useful for the class like number3.
No reason to have both a public variable and a property.
No reason to use goto in a program like that. Prefer while loop.
Find better name for your variables.
You main function should be split in multiple small functions.
Use enum for operations.
Be consistent with your types. Given that the calculator accept 32 bit inputs, you should probably convert user input to 32 bit integers.
Formatting could be improved
And more...

How to split validation from input into two separate methods?

I have the following method and I want to separate the input part from the validation part, i.e. I want to read the input in one method (ReadInput) and to assert that the input value is of type double in another method (AssertIsDouble). How can I do that?
public static double ReadInput()
{
double number = 0;
while (true)
{
if (Double.TryParse(Console.ReadLine(), out number) && number > 0)
{
return number;
}
else
{
Console.WriteLine("Please, input a number greater than zero (0).");
}
}
}
I tried the following but it didn't work:
public static double ReadInput()
{
double number = 0;
while (true)
{
AssertIsDouble(Console.ReadLine());
}
}
private static double AssertIsDouble(string input)
{
double number = 0.0;
if (Double.TryParse(input, out number) && number > 0)
{
return number;
}
else
{
Console.WriteLine("Please, input a number greater than zero (0).");
}
}
I'd use an out parameter along with returning a bool from the Assert method.
Disclaimer: The code is untested but should work.
public static double ReadInput()
{
double number;
while (!AssertIsDouble(Console.ReadLine(), out number))
{
Console.WriteLine("Please, input a number greater than zero (0).");
}
return number;
}
public bool AssertIsDouble(string input, out double number)
{
return (Double.TryParse(input, out number) && number > 0);
}
Note that if I was you I'd also rename the methods as they are a bit unclear at the moment:
ReadInput: Read what input, as what?
AssertIsDouble: Not a bad name but it also does additional checks.
Also note the problem with your original code is this loop:
while (true)
{
AssertIsDouble(Console.ReadLine());
}
You never check/assign the return value from the method call and never set a condition to break out of the loop, thus you have an infinite loop.
What I commonly do to get strongly typed (non-string) input from the user is to have a separate method that takes in a prompt to display to the user, an error prompt to display if they enter an incorrect value, and the min/max values allowed for the input. This greatly simplifies the main code body:
private static double GetDoubleFromUser(
string prompt = "Please enter a number: ",
string errorPrompt = " - Error: input must be a number between {0} and {1}: ",
double minValue = double.MinValue, double maxValue = double.MaxValue)
{
double value;
// Write the prompt text and get input from user
if (prompt != null) Console.Write(prompt, minValue, maxValue);
while (!double.TryParse(Console.ReadLine(), out value)
|| value < minValue || value > maxValue)
{
// If input can't be converted to a double or is out of range, keep trying
if (errorPrompt != null) Console.Write(errorPrompt, minValue, maxValue);
}
// Return converted input value
return value;
}
Now, in your main body of code, you would just do something like:
double input = GetDoubleFromUser("Please input the amount: ",
"- input must be a number greater than zero: ", 0);
Console.WriteLine($"You entered: {input}");
And the method handles the rest:

Unable to use new class constructor values that would overwrite default values in C#

I wrote some code to take in five Social Security Numbers, five gross income entries, and calculate tax for each one. The program will use default values for dollar limit, low rate, and high rate to calculate tax owed. But it will also let user to choose if he/she wants to use their own dollar limit, low rate, and high rate to calculate tax owed for a chosen taxpayer.
Problem:
Whenever I enter my own dollar limit, low rate, and high rate to calculate tax owed it still uses default values (limit = 30000, low rate = .15 and high rate = .28). And that's how a get the wrong calculated tax owed values.
Question.
Could it be because my "public static void GetRates(int income)" doesn't have a return type (it is void)? Should I be returning a value back to main after I call "Taxpayer.GetRates(taxPayer[x].grossIncome);" method?
Part of the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace assignment
{
public class Rates
{
public int incomeLimit; // income limit
public double lowTaxRate; // low tax rate
public double highTaxRate; // high tax rate
public int IncomeLimit // read only property
{
get
{
return incomeLimit;
}
}
public double LowTaxRate // read only property
{
get
{
return lowTaxRate;
}
}
public double HighTaxRate // read only property
{
get
{
return highTaxRate;
}
}
public Rates()
{
DoRates();
}
public void DoRates() // class constructor that assigns default values
{
// set default values for limit, lowRate, and highRate
incomeLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
public void DoRates(int limit, double lowRate, double highRate) // class constructor that takes three parameters
{
incomeLimit = limit;
lowTaxRate = lowRate;
highTaxRate = highRate;
}
// CalculateTax method that takes an income parameter and computes the tax
public int CalculateTax(int income)
{
int taxOwed = 0;
if (income < incomeLimit)
{
taxOwed = Convert.ToInt32(income * lowTaxRate);
}
if (income >= incomeLimit)
{
taxOwed = Convert.ToInt32(income * highTaxRate);
}
return taxOwed;
}
}
public class Taxpayer : IComparable
{
string socialSecurityNum;
int grossIncome;
int taxOwed;
// Use get and set accessors.
public string SocialSecurityNum
{
get
{
return socialSecurityNum;
}
set
{
socialSecurityNum = value;
}
}
// Use get and set accessors.
public int GrossIncome
{
get
{
return grossIncome;
}
set
{
grossIncome = value;
}
}
// Use read-only accessor
public int TaxOwed
{
get
{
return taxOwed;
}
}
// objects are comparable to each other based on tax owed.
int IComparable.CompareTo(Object o)
{
int returnVal;
Taxpayer temp = (Taxpayer)o;
if (this.taxOwed > temp.TaxOwed)
returnVal = 1;
else
if (this.taxOwed < temp.TaxOwed)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
public static void GetRates(int income)
{
int incomeLimit;
double lowRate;
double highRate;
char input;
Rates rates = new Rates();
Console.Write("Do you want default values (enter D) or enter your own (enter O)? ");
input = Convert.ToChar(Console.ReadLine());
switch (char.ToUpper(input)) // start switch
{
case 'D': // if the input latter is d or a D
rates.DoRates();
break;
case 'O': // if the input latter is o or an O
Console.Write("Enter the dollar limit ");
incomeLimit = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the low rate ");
lowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate ");
highRate = Convert.ToDouble(Console.ReadLine());
rates.DoRates(incomeLimit, lowRate, highRate);
rates.CalculateTax(income);
break;
default: Console.WriteLine("You entered and incorrect option"); // display this messages if the input was something other than D or O
break;
}
}
public static void Main()
{
// instantiate an array of five (5) Taxpayer objects.
Taxpayer[] taxPayer = new Taxpayer[5];
Rates taxRates = new Rates();
// Implement a for-loop that will prompt the user
// to enter the Social Security Number and gross income.
for (int x = 0; x < taxPayer.Length; ++x)
{
taxPayer[x] = new Taxpayer();
Console.Write("Enter Social Security Number for taxpayer {0} ", x + 1);
taxPayer[x].socialSecurityNum = Convert.ToString(Console.ReadLine());
Console.Write("Enter gross income for taxpayer {0} ", x + 1);
taxPayer[x].grossIncome = Convert.ToInt32(Console.ReadLine());
Taxpayer.GetRates(taxPayer[x].grossIncome);
taxPayer[x].taxOwed = taxRates.CalculateTax(taxPayer[x].grossIncome);
}
Thank you for the help everyone. I think I did get carried away a little while writing this code. After isolating the code with my issue I finally figured it out. Here is what I did in case anyone wants to see.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace assignment
{
public class Rates
{
public int incomeLimit; // income limit
public double lowTaxRate; // low tax rate
public double highTaxRate; // high tax rate
public int IncomeLimit { get { return incomeLimit; } }// read only property
public double LowTaxRate { get { return lowTaxRate; } } // read only property
public double HighTaxRate { get { return highTaxRate; } }// read only property
public Rates()
{
incomeLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
public Rates(int incomeLim, double lowRate, double highRate)
{
incomeLimit = incomeLim;
lowTaxRate = lowRate;
highTaxRate = highRate;
}
// CalculateTax method that takes an income parameter and computes the tax
public int CalculateTax(int income)
{
int taxOwed = 0;
if (income < incomeLimit)
{
taxOwed = Convert.ToInt32(income * lowTaxRate);
}
if (income >= incomeLimit)
{
taxOwed = Convert.ToInt32(income * highTaxRate);
}
return taxOwed;
}
}
public class Taxpayer
{
string socialSecurityNum = null;
int grossIncome = 0;
int taxOwed = 0;
// Use get and set accessors.
public string SocialSecurityNum { get {return socialSecurityNum;} set {socialSecurityNum = value;} }
// Use get and set accessors.
public int GrossIncome { get { return grossIncome; } set { grossIncome = value; } }
// Use read-only accessor
public int TaxOwed { get { return taxOwed; } }
public void GetRates(int income)
{
int incomeLimit = 0;
double lowRate = 0;
double highRate = 0;
char input;
Console.Write("Do you want default values (enter D) or enter your own (enter O)? ");
input = Convert.ToChar(Console.ReadLine());
switch (char.ToUpper(input)) // start switch
{
case 'D': // if the input latter is d or a D
Rates rates = new Rates();
taxOwed = rates.CalculateTax(income);
break;
case 'O': // if the input latter is o or an O
Console.Write("Enter the dollar limit ");
incomeLimit = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the low rate ");
lowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate ");
highRate = Convert.ToDouble(Console.ReadLine());
Rates myrates = new Rates(incomeLimit, lowRate, highRate);
taxOwed = myrates.CalculateTax(income);
break;
default: Console.WriteLine("You entered and incorrect option"); // display this messages if the input was something other than D or O
break;
}
}
public static void Main()
{
Taxpayer[] taxPayer = new Taxpayer[5];
Rates taxRates = new Rates();
Taxpayer myTaxpayer = new Taxpayer();
// Implement a for-loop that will prompt the user
// to enter the Social Security Number and gross income.
for (int x = 0; x < taxPayer.Length; ++x)
{
taxPayer[x] = new Taxpayer();
Console.Write("Enter Social Security Number for taxpayer {0} ", x + 1);
taxPayer[x].socialSecurityNum = Convert.ToString(Console.ReadLine());
Console.Write("Enter gross income for taxpayer {0} ", x + 1);
taxPayer[x].grossIncome = Convert.ToInt32(Console.ReadLine());
myTaxpayer.GetRates(taxPayer[x].grossIncome);
taxPayer[x].taxOwed = myTaxpayer.taxOwed;
}
// Implement a for-loop that will display each object
// as formatted taxpayer SSN, income and calculated tax.
for (int y = 0; y < taxPayer.Length; ++y)
{
Console.WriteLine("Taxpayer # {0} SSN: {1} income {2:C} Tax is {3:C}", y + 1, taxPayer[y].socialSecurityNum,
taxPayer[y].grossIncome, taxPayer[y].taxOwed);
}
}
}
}
I'll recommend to you to change your code, a more clean code and using betters OOP techniques.
You should check the class Taxpayer, specifically the method called GetRates().
in that method you create a object of type Rates, now, if you check the constructor of the class Rates
public Rates()
{
DoRates();
}
it calls the method Dorates() but without parameters, so, it will always call these DoRates method
public void DoRates() // class constructor that assigns default values
{
// set default values for limit, lowRate, and highRate
incomeLimit = 30000;
lowTaxRate = .15;
highTaxRate = .28;
}
I'm surprised your compiler didn't complain. In Taxpayer.GetRates(int) you make a call to Rates.CalculateTax(int), which returns an int value. It doesn't get stored or returned anywhere, so I'm not sure what the purpose of the call is there. Also, since the object rates is attached to the static method GetRates(int), you're not changing any values in the object taxratesthat you use to calculate the tax. Finally, as has been suggested, your constructor sets default values. You could potentially add another constructor to take parameters. From there, you might want to make sure you change the values in the object you're using to calculate tax.
Occam's razor: keep it simple stupid. I think you're getting carried away with OOP. Simplify some things to make it work.

How to return variables from static void methods

I'm new to C# and strongly typed languages. I'm doing an assignment for university and my program now works as intended. But, I changed 2 static void method headings to have return types not realising doing so will result in marks being deducted.
Current method headings
static bool DispenseCash(double amount, int whichAccount, bool validAmount) and
static double WithdrawAmount(int whichAccount) must remain
What they need to be.
static void DispenseCash(double amount) and
static void WithdrawAmount(int whichAccount)
I changed them because I didn't know how to return the variable amount from
static void WithdrawAmount(int whichAccount)
and use it as a parameter in
static void DispenseCash(double amount).
I am forced to use both methods rather than solve the issue using one larger method.
Here is segments of my code to explain it all a little better. I have only included the relevant parts to keep this short.
int whichAccount = int.Parse(Console.ReadLine());
do
{
double amount = WithdrawAmount(whichAccount);
validAmount = DispenseCash(amount, whichAccount, validAmount);
} while (validAmount == false);
//end of relevant method calls in main
static double WithdrawAmount(int whichAccount)
{
Console.Write("\nPlease enter how much you would like to withdraw: $");
double amount = double.Parse(Console.ReadLine());
return amount;
}
//end WithdrawAmount
In the DispenseCash method that follows if it is instead static void DispenseCash(double amount) how can I pass int whichAccount and bool validAmount into it and return a bool validAmount from it.
private static bool DispenseCash(double amount, int whichAccount, bool validAmount)
{
int numOf20s;
int numOf50s;
double balenceMinusAmount = (accountBalances[whichAccount]) - Convert.ToInt32(amount);
if((Convert.ToInt32(amount) >= 1) && (Convert.ToInt32(amount) % 50 == 0) && (balenceMinusAmount >= accountLimits[whichAccount]))
{
numOf50s = Convert.ToInt32(amount) / 50;
numOf20s = (Convert.ToInt32(amount) % 50) / 20;
Console.WriteLine("Number of 50's = {0}", numOf50s);
Console.WriteLine("Number of 20's = {0}", numOf20s);
accountBalances[whichAccount] = (accountBalances[whichAccount]) - amount;
return validAmount = true;
}
else
{
Console.WriteLine("Invalid entry");
return validAmount = false;
}
}
Remember I can not change the method headings at all. But I can call one of them or new methods inside of the methods. I have tried a few different things, but all attempts have failed.
As mentioned by jdphenix, I am not sure why you are being asked to do it this way. It goes against basic programming principals. Perhaps we do not understand the full context of the question at hand.
The only way I can think of doing it would be to utilise static variables in your application.
private static double withdrawalAmount;
private static int selectedAccount;
private static bool isValidAmount;
Then utilise these in your required methods, e.g.:
public static void WithdrawAmount(int whichAccount)
{
Console.Write("\nPlease enter how much you would like to withdraw: $");
withdrawalAmount = double.Parse(Console.ReadLine());
}

Returning a value from a static void to a static void, that make use of public variables - some guidance please

Just so everyone knows I have literally just started writing C#, and this is practice.
I found a GuessTheNumberGame code on the internet and have been trying to improve the basic game so that feedback is given, and the user can change the numbers.
I had the program working but wanted to put the 'NumberChange' module separate from the 'Code' Method.
I have made a Main() Method inside of my 'GuessTheNumberGame' with executes the 'Code' method.
The thing is when I go to change the number range the 'NumberChange' module won't change the values of 'Public Static int from' or 'Public static int to'; and because of this the range of the numbers remains the same.
Code below:
using System;
namespace GuessThatNumber
{
class GuessTheNumberGame
{
static void Main()
{
Code(from, to, new_range);
}
public static int new_range = 0;
public static int from = 1;
public static int to = 10;
static void Code(int from, int to, int new_range)
{
//int from = 1; // The range the user will guess from.
//int to = 10; //The range the user will guess to.
int guessedNumber; //This will hold the value that the user guessed.
int Counter = 0; //Counter is used to count the number of guesses the user makes.
int selection = 0; //This value is for the selection at the start of the program
//int new_range = 0;
bool exit = false;
while (exit == false)
{
Console.WriteLine("What would you like to do?");
Console.WriteLine("1: Alter the range of guessed numbers? The range is currently from {0} to {1}.", from, to);
Console.WriteLine("2: Try to guess the number?");
Console.WriteLine("3: Exit the program?");
Console.WriteLine("Please enter a number:");
if (int.TryParse(Console.ReadLine(), out selection))
{
if (selection == 2)
{
int randomNumber = new Random().Next(from, to); //Generates a random number between the (from, to) variables.
Console.Write("The number is between {0} and {1}. ", from, to);
while (true)
{
Console.Write("Make a guess: ");
if (int.TryParse(Console.ReadLine(), out guessedNumber))
{
if (guessedNumber == randomNumber)
{
Console.WriteLine("You guessed the right number!");
if (Counter < 2)
{
Console.WriteLine("You guessed the number in only 1 turn! Amazing!");
Console.WriteLine(" ");
}
else
{
Console.WriteLine("You guessed " + Counter + " times.");
Console.WriteLine(" ");
}
break;
}
else
{
Console.WriteLine("Your guess was too {0}.", (guessedNumber > randomNumber) ? "high" : "low");
Counter = Counter + 1;
}
}
else
{
Console.WriteLine("Input was not an integer.");
}
}
//Console.WriteLine();
//Console.WriteLine("Press any key to exit.");
//Console.ReadKey();
}
else if (selection == 1)
{
NumberChange(from, to, new_range);
}
else
{
exit = true;
}
}
}
}
static int NumberChange(int from, int to, int new_range)
{
Console.WriteLine("Please enter the number that the guess will start from.");
int.TryParse(Console.ReadLine(), out new_range);
from = new_range;
Console.WriteLine("Now enter the number that the guess will go to.");
int.TryParse(Console.ReadLine(), out new_range);
to = new_range;
return new_range;
}
}
}
Please read about passing parameters by reference in C#.
So far, your parameters are passed by value. That means that upon calling Code() in the beginning of your program, the current values of public static int from and public static int to are copied into the parameters from and to.
The same happens when you invoke NumberChange(): The values of the parameters (local variables) from and to are copied into the parameters of the NumberChange() method with the same names, but if those values are modified within NumberChange, the new values don't ever get back from there; you have just modified the local variables from and to that only exist within the respective method.
Instead, you could declare your parameters using the ref keyword:
static int NumberChange(ref int from, ref int to, int new_range)
This means that you will have to invoke your method using the ref keyword for the respective arguments, too:
NumberChange(ref from, ref to, new_range);
Also, note two issues about your NumberChange() method:
You pass in a new_range argument, but you do not use it. In fact, it is overridden in your call to TryParse(). Therefore, you could simply declare int new_range as a local variable rather than passing it as a parameter.
You return a value from that method, but you do not use that value. Therefore, you could declare your method as void and drop the return statement.
Lastly, if you want your public static int from and public static int to variables to be changed by Code(), add the ref keyword analogously to NumberChange(). However, this is not really useful with your current code, as the program ends right after leaving Code() and the new values wouldn't be used at all.
You are using static variables, then passing them into a method that has access to them already. Passing them in essentially overrides the static versions with the local ones.
Change your method to this:
private static void NumberChange()
{
int new_range;
Console.WriteLine("Please enter the number that the guess will start from.");
int.TryParse(Console.ReadLine(), out new_range);
from = new_range;
Console.WriteLine("Now enter the number that the guess will go to.");
int.TryParse(Console.ReadLine(), out new_range);
to = new_range;
}
static void Code()
{
}
And delete this line:
public static int new_range = 0;
If you pass your variables by reference. Then the function your passing them can change them.
something like this
static int NumberChange(ref int from, ref int to, ref int new_range)
{
//Your code here
}
Adn the same for your Code method

Categories