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)); //<-
}
Related
I'm currently reading trough a C# tutorial. Now I came across this:
using System;
namespace RectangleApplication {
class Rectangle {
//member variables
protected double length;
protected double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double GetArea() {
return length * width;
}
public void Display() {
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}//end class Rectangle
class Tabletop : Rectangle {
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost() {
double cost;
cost = GetArea() * 70;
return cost;
}
public void Display() {
base.Display();
Console.WriteLine("Cost: {0}", GetCost());
}
}
class ExecuteRectangle {
static void Main(string[] args) {
Tabletop t = new Tabletop(4.5, 7.5);
t.Display();
Console.ReadLine();
}
}
}
In the class Tabletop there is cost declared twice. Once as private double cost; and 4 lines later as double cost;
Why is that so?
When removing double cost; the Code still works. When double cost is in the code I can hover over private double cost; and read the message: The field Tabletop.cost is never used". I pretty much can remove either of the cost and the code works fine.
Did they forget to remove one of the declareation or is there a reason behind?
Also, why don't I get an error message like "cost is already defined"?
Here is the Tutorial link
private double cost; is unused and can be removed.
You don't get an error because as John said in the comments, it's in different scopes; one is defined as a field of the class while the other is a local variable. When cost is used, the local variable is accessed. To access the field, this.cost can be used.
class A
{
private int a = 1;
void A()
{
int a = 2;
Console.WriteLine(a); // 2
Console.WriteLine(this.a); // 1
}
}
Note you cannot have multiple local variables with the same name, even in different scopes:
void A()
{
int a = 1;
if(someCondition)
{
int b = 2; // Compiler error: A local variable named 'a' cannot be declared in this scope because it would give a different meaning to 'a', which is already used in a 'parent or current' scope to denote something else
}
}
In fact, in your class Tabletop, the scopes cost is overlapped because there is also a local variable named cost in the method GetCost.
Within the scope of GetCost, when you refer to cost, you are actually referring to the locally scoped object named cost and not the one in the outer scope (the one in the class). When this happens, the cost declared in the outer scope is hidden by the inner scope(in the method).
When defining a variable in a member-scope (in your case within a method) that has the same name as an existing member, you just hide the latter and reference the former.
So in your example:
class Tabletop : Rectangle
{
private double cost;
public Tabletop(double l, double w) : base(l, w) { }
public double GetCost()
{
double cost; // this hides the field
cost = GetArea() * 70;
return cost; // this referts to the variable defined two lines above
}
public void Display()
{
Console.WriteLine("Cost: {0}", cost); // while this refers to the field
}
}
cost from within GetCost will refer to the local variable, while using cost in Display for example will refer to the field.
This is absoluetely fine. However it can yield to confusion and thus unexpected behaviour. This is why some developers tend to use the this-qualifier:
public double GetCost()
{
double cost;
this.cost = GetArea() * 70;
return this.cost;
}
with the qualifier you refer to current instance, making this.cost` an access to your field instead of to the variable.
I think they do forget to remove it.
As why you don't get "cost is already defined" error, it's because the double cost in GetCost() is local (only accessible inside GetCost() method, and will be destroyed from memory after GetCost() method completed), while the private double cost is available to the entire Tabletop class to be accessed and will be kept in memory as long as the Tabletop instance live.
In the class Tabletop there is cost declared twice. Once as private
double cost; and 4 lines later as double cost;
Well private double cost; is a member field for tableTop class whereas other declaration is local to the method body. Why there is a confusion.
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.
using System;
//Find the square root of a number for 10 values from user
class forLoop
{
static void Main
{
double x;
for(int i=10; i>0 && x>=0; i--)
{
Console.WriteLine("You have {0} remaining calculations left", i);
Console.Write("Please enter a positive number: ");
x = double.Parse((Console.ReadLine());
x = Math.Sqrt(x);
Console.WriteLine("The square root is {0}", x);
Console.WriteLine("");
}
Console.WriteLine("You have 0 remaining calculations left");
}
}
I need help on this C# problem: Why does the error: "A get or set accessor expected" come up at compile time?
You missed the () in method declaration. Thus, the compiler thinks at some level that you're declaring a Property (albeit it would then throw an error about the void type), not a Method
// Property
public int Property
{
get { return _field; }
set { _field = value; }
}
// Property, albeit a get-only property
public int Property => _field;
// Method
public int Method()
{
return _field;
}
// Method
public int Method() => _field;
UPDATE: Since this is still being seen, I've updated the example values to better reflect their underlying types, and included examples of expression bodies introduced with C# 6
You need parentheses (()) in the method declaration.
Parentheses is required to differentiate a method from a property that requires the get/set syntax
Im trying to use this method called GetDouble but i keep getting the error "no overload for method 'GetDouble' takes 1 arguments" and i have no idea how to fix it.
public static bool GetDouble(string StringToConvert, out double dblOutValue)
{
return double.TryParse(StringToConvert, out dblOutValue);
}
im calling it from this method
private bool ReadAndValidatePrice(out double price)
{
price = 0.0;
if (!InputUtility.GetDouble(txtPrice.Text))
{
}
}
Any help trying to fix it is appriciated, thanks.
As the error is trying to tell you, GetDouble() takes two arguments.
The second argument is an out parameter, meaning that it will set the variable you pass to it as a result.
When calling it, you must pass a variable with the out keyword.
You have a few issues here. The first is your GetDouble method. What are you trying to do? If you are trying to just get the double (as the name implies) then it should be more like
public static double GetDouble(string StringToConvert)
{
double dblOutValue;
double.TryParse(StringToConvert, out dblOutValue);
return dblOutValue;
}
Then look at your ReadandValidatePrice method. With the above change it should be more like:
private bool ReadAndValidatePrice(out double price)
{
price = InputUtility.GetDouble(txtPrice.Text)
//not sure if the IF statement is needed anymore so it is omitted
}
How is that? Where my assumptions completely wrong?
You miss one parameter ,GetDouble() takes two parameters. But you have pass one parameter, So you got that error . Now try below method instead of your method .
private bool ReadAndValidatePrice(out double price)
{
price = 0.0;
if (!InputUtility.GetDouble(txtPrice.Text, out price ))
{
}
}
Your method should look like follow, because your GetDouble() method defines two parameter:
private bool ReadAndValidatePrice(out double price)
{
price = 0.0;
if (!InputUtility.GetDouble(txtPrice.Text, out price))
{
}
}
I want my object to be able to type in an double or a string such as getting an input for salary. I have my code working with a property that allows for a double only. I know that property overloading isn't supported from the other postings at this site. I also know that setters are going to allow me to get an string input for salary. I don't understand how to overload. I have some of the template code here:
private double salary = 20000;
public Employee()
{
}
public Employee(double sal)
{
salary = sal;
}
public double Salary
{
get { return salary; }
set { salary = value; }
}
public void SetSalary(string sal)
{
salary = Convert.ToString(sal);
}
Error code:
can not implicitly covert type string to double
I want to be able to have an object be able to overload salary using a setter in C#. I am a student and understand most of the basics. Thanks ahead of time for any help.
public void SetSalary(string sal)
{
salary = Convert.ToString(sal);
}
You are converting the parameter, which is already a string, to a string, and trying to assign it to a field that is of type double.
salary = Convert.ToDouble(sal); // one way
salary = double.Parse(sal); // another way
Note that these conversions can fail if the string is not in the proper numeric format. double.TryParse could be useful, but it's probably an exception that needs to propogated to your callers when they send an invalid input. With all of that said, I would leave it up to your callers to convert the value to the appropriate type and simply expose the double property. There's no need to complicate matters in your class.
For that matter, for a value that is supposed to represent a salary, you should consider using the more appropriate decimal type. It's tailored for storing financial values.
decimal salary;
// elsewhere
salary = Convert.ToDecimal(sal);
salary = decimal.Parse(sal);
This will get rid of the error you are describing:
public void SetSalary(string sal)
{
salary = Convert.ToDouble(sal);
}
The offending line is
salary = Convert.ToString(sal);
This says: set the salary private field to be whatever the string representation of sal is. But the salary private field is actually a double! You probably want something like
public void SetSalary(string sal)
{
salary = double.Parse(sal);
}
Or, if you don't like to use exceptions for errors, use double.TryParse instead.
salary = Convert.ToString(sal);
You are converting the string sal again to string by ToString? And then you are trying to assign it to a double salary.
// Note that this has been shortened. The compiler will take care of making a backing field for us; we don't need to worry about it.
public double Salary { get; set; }
public Employee()
{
// Only set the default value for Salary in the parameterless constructor.
Salary = 20000.0;
}
public Employee(double salary)
{
// Notice how the parameter names are more verbose.
Salary = salary;
}
public void SetSalary(string value)
{
double salary;
// TryParse allows us to handle errors manually, rather than dealing with (slow) exceptions.
if (double.TryParse(value, out salary))
{
Salary = salary;
}
else
{
// We should really do something other than just throw an exception here, but that's what I'm doing for example purposes.
throw new ArgumentException("Argument must be parsable as a double.", "value");
}
}