I want to be able to use the "costOfCar" function in the "InterestPaid" function. I would appreciate any help.
namespace Functions9
{
class Program
{
static void Main(string[] args)
{
Double userCarCost, userDownPayment, userInterestRatePercentage, test; //declares "userCarCost" , "userDownPayment variable", "userInterestRatePercentage"
Console.WriteLine("This program will do some calculations for you about a car loan."); //explains the purpose and function of program to user
Console.WriteLine(); //adds an empty line
Console.WriteLine("What is the cost of your new car?"); //prompt user for input
userCarCost = Convert.ToDouble(Console.ReadLine()); //converts user input regarding car cost to double and stores in "userCarCost" variable
Console.WriteLine(); //adds an empty line
Console.WriteLine("How much money will you put as a down payment");
userDownPayment = Convert.ToDouble(Console.ReadLine()); //converts user input regarding down payment to double and stores in "userDownPayment" variable
Console.WriteLine();
Console.WriteLine("What is your interest rate percentage? Put a point before the number");
userInterestRatePercentage = Convert.ToDouble(Console.ReadLine()); //converts user input regarding interest rate to double and stores in "userInterestRatePercentage" variable
Console.WriteLine(); //adds an empty line
Console.WriteLine("How many years before you pay back the loan?");
CostOfCar(userCarCost, userDownPayment);
}
static double CostOfCar(double number1, double number2)
{
double costOfCar = number1 - number2; //"costOfCar" variable is determined by subtracting "userCarCost", "userDownPayment"
return costOfCar; // returns the cost of the car to the main method
}
static double InterestPaid(double number1, double number2)
{
double interestPaid = number1 * number2;
return interestPaid;
}
}
}
Just call it?
static double InterestPaid (double number1, double number2)
{
double interestPaid = number1 * number2 * CostOfCar(number1, number2);
return interestPaid;
}
Or with the correct formula you need.
(update according remark):
static double InterestPaid (double number1, double number2)
{
var costOfCar = CostOfCar(number1, number);
double interestPaid = number1 * number2 * costOfCar;
return interestPaid;
}
Btw, it is better to name functions with a verb, like CalculateCostOfCar.
You need something to capture the value.
In Main, instead of
CostOfCar(userCarCost, userDownPayment);
write
double cost = CostOfCar(userCarCost, userDownPayment);
Here, the variable cost is capturing the returned value from the function for later use.
static double InterestPaid (double number1, double number2)
{
var val=Program.CostOfCar(number1, number2);
double interestPaid = number1 * number2;
var total=val+interestpaid;
return total;
}
Related
I am trying to build a BMI calculator and I the only thing that can be in the main function is method calls. Whenever i run the following code, the calculation answer does not print. How can i fix that?
public static Double EnterWeight(object sender, EventArgs e)
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight(object sender, EventArgs e)
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight(object sender, EventArgs e);
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
Console.WriteLine("Your BMI is: ", BMI);
}
There are some extra lines in the mine that I used for testing.
The result is just a blank
It looks like there are several problems with the code, though they are small. First, you define methods that take in parameters that are not used, like object sender and EventArgs e. You should only define arguments to a method if they are used inside the method, so you can remove those in your case.
Secondly, when you call EnterWeight, you're defining the variables inside the method call, rather than defining them before-hand and then passing them in using the variable names (which would be the way to solve this issue). But since the method doesn't actually require them, they can be removed from the method and therefore removed from the call.
Finally, when writing methods to get strongly-typed input from the user, it is sometimes nice to create a more flexible method that takes in a string used for the "prompt" for the input, and then use the TryParse methods in a loop, which continually loops until they enter valid input. This way you can re-use the same method to get a double from the user and just pass in different prompts.
For example:
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
private static double GetDoubleFromUser(string prompt)
{
double input;
// double.TryParse attempts to convert a string into a double, and
// it returns a bool that indicates success. If it's successful,
// then the out parameter will contain the converted value. Here
// we loop until we get a successful result, then we return the value.
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out input));
return input;
}
public static double GetBMI(double height, double weight)
{
return weight / Math.Pow(height, 2) * 703;
}
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static void Main()
{
string name = GetStringFromUser("Enter your name: ");
double weight = GetDoubleFromUser("Enter your weight in pounds: ");
double height = GetDoubleFromUser("Enter your height in inches: ");
double bmi = GetBMI(height, weight);
Console.WriteLine($"Thank you, {name}. Your BMI is: {bmi}");
GetKeyFromUser("\n\nDone! Press any key to exit...");
}
You are using the Console.WriteLine incorrectly. You need to use {argumentNumber} to indicate what argument to print and where in the string. Considering the following (I had to make some additional adjustments to get your code to compile. However, to answer your direct question, your BMI is not printing out because you are using Console.WriteLine slightly wrong.
public static Double EnterWeight()
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight()
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
//string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight();
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
// Notice the {0}. I tell it where in the string to print the
// argument I passed in out, and the number indicates which argument
// to use. Most of .NET formatting works like this.
Console.WriteLine("Your BMI is: {0}", BMI);
}
And additional strategy is to use the $"" string where you can do the following:
Console.WriteLine($"Your BMI is: {BMI}");
I'm learning C#. (6 hours in) I'm more comfortable with Ruby and Javascript and am finding C# fun, yet way tighter in what it will allow you to do, so I am rediscovering simple functions. I'm trying to build a simple calculator just to transition to the C# way of doing things and I keep hitting scope issues.
Here's the code. The NumSelect function is breaking it. I want a user to be able to type in 2 numbers in the console and then they'll be added. Once that works I'll create other math operations and throw in some logic to have the user select with operation they would like to do and then ask them for their inputs and then do the calculation.
The error is
calculator.cs(18,9): error CS0103: The name `number1' does not exist in the current context
and it's hitting it at very instance of number1 and number2 beyond the NumSelector function. So it seems like a scope issue, but I can't figure out the right approach for assigning these variables in a function so I only have to do it once.
using System;
class SimpleMath
{
public int Add(int number1, int number2)
{
int result = number1 + number2;
return result;
}
public int Subtract(int number1, int number2)
{
int result = number1 - number2;
return result;
}
//this function will assign the inputs to variables
public int NumSelect()
{
number1 = Console.ReadLine;
number2 = Console.ReadLine;
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
operation.NumSelect();
int result = operation.Add(number1, number2);
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
}
}
Well you need to decide whether these numbers are meant to be part of the state of your object or not. If they are, make them fields. If they're not, don't. In this case, I'd probably keep them as local variables and change your NumSelect code to simply return one number entered by the user - and call it twice:
public int NumSelect()
{
string line = Console.ReadLine();
return int.Parse(line);
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
int number1 = operation.NumSelect();
int number2 = operation.NumSelect();
int result = operation.Add(number1, number2);
Console.WriteLine("{0} + {1} = {2}", number1, number2, result);
}
You could change your whole class to make the values fields, and remove the parameters, like this:
class SimpleMath
{
private int number1;
private int number2;
public int Add()
{
int result = number1 + number2;
return result;
}
public int Subtract()
{
int result = number1 - number2;
return result;
}
public int SelectNumbers()
{
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
}
static void Main()
{
SimpleMath operation = new SimpleMath();
Console.WriteLine("Give me two numbers and I will add them");
operation.NumSelect();
int result = operation.Add();
Console.WriteLine(
"{0} + {1} = {2}",
operation.number1,
operation.number2,
result);
}
}
This doesn't feel like the best approach to me - I'd take the earlier approach of using local variables in Main - but I wanted to show you the alternative. Note that you can only access operation.number1 in Main because the Main method is in the same type - that should raise warning bells for you.
Put your two numbers as class fields rather than methods'.
int number1 = 0, number2 = 0; //have them as class fields like this
public int NumSelect()
{
number1 = Console.ReadLine();
number2 = Console.ReadLine();
}
This way, you could access your number1 and number2 across different methods.
Method's fields/arguments are only valid within the method:
//number1 and number2 are method arguments, only accessible in the method
public int Add(int number1, int number2)
{
int result = number1 + number2;
return result;
}
//not accessible elsewhere
public int NumSelect() //number1 and number2 are unknown in this method
{
number1 = Console.ReadLine();
number2 = Console.ReadLine();
}
Just take two simple input from user in Main(). Like:
number1 = int.Parse(Console.ReadLine());
number2 = int.Parse(Console.ReadLine());
And then send it to your method Like:
int result = operation.Add(number1, number2);
otherwise declare the variables in the Field so that you can use them anywhere in the class.
I'm still in the middle of my programming assignment trying to use methods to make a calculator, and I am getting:
Member 'LabAssignFiveCalc.Sum.Addition(double, double)' cannot be accessed with an instance reference; qualify it with a type name instead
on this line of code
Sum s = new Sum();
if (metUse == "Addition")
result = s.Addition(num1, num2);
Here's the entire file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LabAssignFiveCalc
{
public class Sum
{
//Addition method
public static double Addition(double num1, double num2)
{
double result;
result = num1 + num2;
return result;
}
//Subtraction method
public static double Subtract(double num1, double num2)
{
double result;
result = num1 - num2;
return result;
}
//Multiplication method
public static double Multiply(double num1, double num2)
{
double result;
result = num1 * num2;
return result;
}
//Division method
public static double Divide(double num1, double num2)
{
double result;
result = num1 / num2;
return result;
}
}
public class Program
{
//Main
static void Main(string[] args)
{
//Declare Variables
int choice;
string op;
double num1;
double num2;
double result;
string metUse;
//Ask user for calculation parameters
Console.WriteLine("Calculator:");
Console.WriteLine("Which operation do you wish to perform? Type the corresponding number.");
Console.WriteLine("1) Addition\n2) Subration\n3) Multiplication\n4) Division");
choice = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type the first number you wish to calculate");
num1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please type the second number you wish to calculate");
num2 = Convert.ToDouble(Console.ReadLine());
//Declare Operator
switch (choice)
{
case 1:
op = "+";
metUse = "Addition";
break;
case 2:
op = "-";
metUse = "Subtract";
break;
case 3:
op = "*";
metUse = "Multiply";
break;
case 4:
op = "/";
metUse = "Divide";
break;
default:
throw new ArgumentException();
}
Sum s = new Sum();
if (metUse == "Addition")
result = s.Addition(num1, num2);
//Show Calculation
Console.WriteLine("{0}{1}{2}={3}", num1, op, num2, result);
Console.ReadKey();
}
}
}
Like I said, I'm still a beginner so go easy on me please :P It's probably some really rookie error.
Thanks for the help :D
Addition is a static method.
You cannot call a static method using an instance of a type; call it with the type itself.
Try this instead:
if (metUse == "Addition")
result = Sum.Addition(num1, num2);
The Addition member of the Sum class is marked as static. This means it cannot be called on an instantiated class. Do this instead:
result = Sum.Addition(num1, num2);
As the addition is a static method in Sum class, then it can be accessed as sum.addition(a,b);
and you don't have to create an object to use it.
The application shall perform the selected menu math operation on the two entered numbers and display the answer.You must use methods for each math operation and a decision must be used to pick which method should be executed.
The application shall display an error message when a correct menu number is not entered. This is a decision where 1-5 are valid selections and everything else is “Invalid”.
The application shall not allow division by zero. Do not perform the divide operation if the second number variable is zero, but instead display an error message.
I have written the code but the program is showing the following error:
1. No overload for method AddNumber takes 0 arguments. this error is showing for all math operation methods inside the switch statements.
2. For DivideNumber method - not all code paths return a value
class Program
{
static void Main(string[] args)
{
double n1 = Convert.ToDouble(Console.ReadLine());
//string n2 = "";
double n2 = Convert.ToDouble(Console.ReadLine());
Console.Clear();
Console.WriteLine("Simple Calculator");
Console.WriteLine("\t 1) ADD");
Console.WriteLine("\t 2) SUBTRACT");
Console.WriteLine("\t 3) MULTIPLY");
Console.WriteLine("\t 4) DIVIDE");
Console.WriteLine("\t 5) QUIT");
Console.Write("Enter Selection: ");
int menuSelection =0;
// double total;
// menuSelection = Console.ReadLine();
switch (menuSelection)
{
case 1:
// total = Convert.ToInt32(AddNumbers("Results:"));
Console.WriteLine(AddNumbers(n1,n2));
break;
case 2:
Console.WriteLine(SubtractNumber(n1,n2));
break;
case 3:
Console.WriteLine(MultiplyNumber(n1,n2));
break;
case 4:
Console.WriteLine(DivideNumber(n1,n2));
break;
case 5:
break;
default:
Console.WriteLine("Invalid Selection !");
Console.ReadLine();
return;
}
//Ask user to enter two numbers
Console.WriteLine();
Console.Write("Enter Number 1:", n1);
// number1 = Console.ReadLine();
Console.Write("Enter Number 2:", n2);
// number2 = Console.ReadLine();
}
public static double AddNumbers(double number1, double number2)
{
return number1 + number2;
}
public static double SubtractNumber(double number1, double number2)
{
return number1 - number2;
}
public static double MultiplyNumber(double number1, double number2)
{
return number1 * number2;
}
public static double DivideNumber(double number1, double number2)
{
if (number1 == 0 && number2 == 0)
{
Console.WriteLine("Cannot Divide by Zero. Try Again");
return 0;
}
else
{
return number1 / number2;
}
}
1st mistake You are taking input after calling switch cases
2nd mistake your function have two parameters so pass them.
like DivideNumber(number1,number2) in your switch case
hope you understand
one thing i notice is you are taking input in string and your function takes double parameters so you need to convert string to double.
Give you idea use double to take input like double n1 = Convert.ToDouble(console.readline()); as input from console is string.
you are calling your function return AddNumbers();
but have declared it as public static double AddNumbers(double number1, double number2)
AddNumbers expected 2 numbers, you have passed 0.
You don't return anything from DivideNumbers, though you have declared it to return a double. public static double DivideNumber
The program makes no sense as it is. You are trying to do the operation before they've even given you the numbers. You should try to Rubber Duck this one yourself
This should do what your trying to accomplish.
I'm pretty new to c# and am confused on how to set the data members and then calculate the tax with a different method. Here is what this part of the program should do:
"If the user selects default the default values you will instantiate a rates object using the default constructor and set the Taxpayer class data member for tax equal to the value returned from calling the rates object CalculateTax method."
-I have a switch statement calling for the default constructor if they choose 'D', I'm not sure how to set the taxpayer class data to default, i'm not sure if the CalculateTax method is correct either.
and then do the same type of thing if they choose 'O'
Here is what I have so far:
using System;
interface Icomparable
{
int CompareTo(Object o);
}
class rates
{
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
private rates()
{
Limit = 30000;
LowRate = 0.15;
HighRate = 0.28;
}
public rates(double Limit; double LowRate; double HighRate;)
{
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
}
public CalculateTax()
{
if(Income < Limit)
{TaxOwed = (Income * LowRate)}
else
{TaxOwed = (Income * HighRate)}
}
}
public class taxpayer : IComparable
{
public string SSN{get; set;}
public double Income{get; set;}
public double TaxOwed{get;}
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 getRates()
{
double Limit;
double LowRate;
double HighRate;
Console.WriteLine("Do you want default values(enter D) or enter your own (enter O)?");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case'D':
rates();
break;
case'O':
rates(double Limit; double LowRate; double HighRate;)
break;
default:
Console.WriteLine("Invalid input");
goto getRates();
}
}
}
Any help with this would be very much appreciated.
I don't see why you would keep re creating an object that you have all the values for.
Here is an alternate pattern, static presets + factory
class Rates
{
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
static readonly Rates default = new Rates(30000,0.15,0.28);
static readonly Rates govna = new Rates(300000,0.1,0.2);
static readonly Rates priest = new Rates(300,0.05,0.07);
public static Rates createRates()
{
double Limit; double LowRate; double HighRate;
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
return new Rates( Limit, LowRate, HighRate );
}
private Rates(double limit; double lowRate; double highRate;)
{
Limit = limit;
LowRate = lowRate;
HighRate = highRate;
}
public double CalculateTax( double Income)
{
if(Income < Limit)
{return (Income * LowRate)}
else
{return (Income * HighRate)}
}
}
Oh and whats with goto?
while( null == ratesResult ){
Console.WriteLine("Do you want default values(enter D) or enter your own (enter O)?");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case'D':
ratesResult = Rates.default;
break;
case'O':
ratesResult = Rates.createRates();
break;
default:
Console.WriteLine("Invalid input");
}
}
You have many problems with your code, buddy. Here is some advice that might guide you in the right direction.
In the following properties, you should also have a set; accessor to be able to store those values.
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
In the following function, do you want to prompt the user to enter values? If so, change the first line from
public rates(double Limit; double LowRate; double HighRate;)
to
public rates(bool dummy)
Now your code will look like
public rates(bool dummy) //Note that dummy is not used in this function. It just distinguishes rates() from rates(bool)
{
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
}
the dummy is just to allow the the code to distinguish your two different functions.
In your switch statement, just call the rates(bool dummy) function instead of the other one. For the dummy, assign it either true or false, who cares.... It'd look like the following.
switch (entry) //set switch
{
case'D':
rates();
break;
case'O':
rates(true)
break;
default:
Console.WriteLine("Invalid input");
goto getRates();
}
There's more problems with your code, but you have to revise it before we can help you further. You should actually try to use it in VS, since the editor can help you fix problems by giving you specific errors.