When I type in the textbox, I am wanting it to add the numbers, instead if I type (for example) 12, and click deposit again, it only shows 12. I think this is because it seems to think thats its 0 plus 12 everytime. Something doesnt seem to be instantiating correctly. I think. Can anyone point out what I am doing incorrectly?
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_deposit_Click(object sender, EventArgs e)
{
double input;
input = double.Parse((putin.Text));
BankAccount a = new BankAccount(input);
aMtBox.Text = a.AccountBalance.ToString();
}
}
public class BankAccount
{
private double num1;
private double accountBalance;
public BankAccount(double input)
{
num1 = input;
Deposit();
}
public double Num1
{
set {num1 = value;}
get {return num1;}}
public double AccountBalance
{
get {return accountBalance;}
set {accountBalance = value;}}
public void Deposit()
{
accountBalance = accountBalance + num1;
}
}
}
You're creating a new instance of BankAccount each time the button is clicked - so accountBalance will be 0.0 (the default value for a field of type double). How did you expect it to "know" about the previous balance?
It's entirely possible that you should have an instance variable of type BankAccount in your form. You should also consider what the num1 instance variable in BankAccount is meant to represent. The name certainly doesn't tell us anything. It feels like it should actually just be a parameter to the Deposit method.
Additionally, for currency values you should never use double - use either decimal, or an integer type to represent the number of cents (or pence, or whatever). You don't want to get into the normal binary floating point issue.
At this point, your method would become something like:
// I hate the VS-generated event names, but...
private void btn_deposit_Click(object sender, EventArgs e)
{
// TODO: Use decimal.TryParse, and handle invalid input cleanly.
decimal newDeposit = decimal.Parse(putin.Text);
account.Deposit(newDeposit);
aMtBox.Text = account.AccountBalance.ToString();
}
You need to have a BankAccount field for the form which is initialized with the form. Should look something like this:
public partial class Form1 : Form
{
private BankAccount account;
public Form1()
{
InitializeComponent();
account = new BankAccount(0);
}
private void btn_Deposit_Click(object sender, EventArgs e)
{
account.Num1 = double.Parse((putin.Text));
account.Deposit();
aMtBox.Text = account.AccountBalance.ToString();
}
}
On a side note, Input should be validated, and the BankAccount class refactored to something like:
class BankAccount
{
private double num1;
private double accountBalance;
public BankAccount(double startingBalance)
{
accountBalance = startingBalance;
}
public double AccountBalance
{
get {return accountBalance;}
set {accountBalance = value;}
}
public void Deposit(double depositAmount)
{
accountBalance += depositAmount;
}
}
Related
Maybe this is a very silly question but it's been a long time I worked with VS.
I'm trying to figure out how I can call a method/function from inside my program e.g. by pressing a button. But the method is written in Class1.cs. I show below what I'm trying but I know this is completely wrong:
namespace TestProject1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
AddingNumbers(3, 5);
label1.Text = Result;
}
}
}
And in Class1.cs I have something like this:
namespace TestProject1
{
class Class1
{
public static AddingNumbers(int num1, int num2)
{
return num1 + num2;
}
}
}
If someone could help me understand this I would really appreciate. I don't need a full answer because then I won't learn anything.
I think it has to do with Public, Static, Void or something like this. I have tried to understand how this principle works by reading on MSDN but I don't grasp it for now.
Advice would be appreciated
I think you have missed return type of AddingNumbers method it would be as follows
public static int AddingNumbers(int num1, int num2)
{
return num1 + num2;
}
And in Form1 class you can called AddingNumbers(static method) by it's class name as follows
private void button1_Click(object sender, EventArgs e)
{
var Result = Class1.AddingNumbers(3, 5);
//As per your requirement you need to show it in label that's
//why used ToString() method to convert from int to string
label1.Text = Result.ToString();
}
Accessing static method within a class still require you to call the full namespace. Therefore you should be calling it using Class1.AddingNumbers(3, 5);
And your static method need a return type int
I am learning about writing constructors and properties in c# and was asked to write a console app and class to operate a beverage machine. I wrote part of the class code but ran into an issue. One of the many blocks of code asks for a constructor method that starts the SodaCanCount at 5 bottles and sets the CustBalance field to zero. I don't know what this constructor should look like. I am specifically talking about the private sodaVandorClass(), right under the two private fields.
I wrote what I could so far and I have no errors however the SodaVendorClass does not look right.
namespace VendorClass
{
public class SodaVendorClass
{
// members
// fields
//Customer balance is $0 until the customer inserts a dollar
//All customer entries are one dollar increments and a soda costs one dollar.
private int CustBalance = 0;
//a machine holds 10 cans of soda
private int SodaCanCount = 5;
//A soda costs 1 dollar
//private int sodaCost = 1;
public int _SodaCanCount
{
get
{
return SodaCanCount;
}
}
public int _CustBalance
{
get
{
return CustBalance;
}
}
public int BuySoda(int pCustBalance, int SodaCanCount)
{
return SodaCanCount;
}
public void AcceptCash(int CustBalance)
{
CustBalance++;
}
public int GiveRefund(int pCustBalance)
{
return CustBalance;
}
}
I only want to see an example of a constructor that sets default values for my private class fields. Any help will be appreciated.
You can define a public constructor like below but probably you don't need one if you enable your properties to set values too
public SodaVendorClass()
{
this.CustBalance = 0;
this.SodaCanCount = 0;
}
You can make your properties writable too. Notice below are auto properties and in such case you don't need those private backing fields explicitly.
public int SodaCanCount
{
get; set;
}
public int CustBalance
{
get; set;
}
You can instantiate your type saying (using Object Initializer construct)
SodaVendorClass sc = new SodaVendorClass
{
SodaCanCount = 10,
CustBalance = 500,
};
A constructor for this class could look like this:
public SodaVendorClass () {
}
That would be an empty constructor that does nothing.
To set the two values you want, you can add some paramters:
public SodaVendorClass (int customerBalance, int sodaCount) {
this.CustBalance = customerBalance;
this.SodaCanCount = sodaCount;
}
To create an instance of this class with 5 soda cans and a customer balance of 0, you would call the constructor in the code like this:
var vendor = new SodaVendorClass(0, 5);
namespace VendorClass
{
public class SodaVendorClass
{
private int CustBalance;
private int SodaCanCount;
//...
public SodaVendorClass() // default constuctor
{
CustBalance = 0;
SodaCanCount = 5;
}
//...
}
}
Default constructor is called when you are creating object like this:
SodaVendorClass obj = new SodaVendorClass();
So obj._SodaCanCount is 5 and obj._CustBalance is 0
Also you can define constructor with parameters.
public SodaVendorClass(int balance, int count)
{
CustBalance = balance;
SodaCanCount = count;
}
and create call this constructor.
SodaVendorClass obj = new SodaVendorClass(0, 5);
A constructor is being used while creating a object like "Class obj=new Calss()". If you don define a constructor in your class a default constructor will be provided implicitly.User defined Constructor usually used for initializing value for class properties. Unlike function constructor does not have any return type at all not even void. All the answers are good.
public class SodaVendorClass{
private int CustBalance = 0;
//a machine holds 10 cans of soda
private int SodaCanCount = 5;
//A soda costs 1 dollar
//private int sodaCost = 1;
public int _SodaCanCount
{
get
{
return SodaCanCount;
}
}
public int _CustBalance
{
get
{
return CustBalance;
}
}
public SodaVendorClass(int cancount, int sodacost){
SodaCanCount=cancount;
sodaCost=sodacost;
}
}
//creating a object of Sodavendorclass
Sodavendorclass obj=new Sodavendorclass(0,0); //Provided value for class property
Notice that at the time of object creation, provided for Property. This is one of the way you can use constructor.
I am trying to make an integer = numericupdown not within a method. What I am trying to say is I want to initialize an integer that can be used every where in the main form.
int number1 = Convert.ToInt32(numericUpDown1.Value);
I want to define it before I call any events so I can use it everywhere. Thanks
Create a static class and set your property number1 to a static property.
public static class KeySets
{
public static int Number1 { get; set; }
}
then set property
KeySets.Number1 = Convert.ToInt32(numericUpDown1.Value);
then you can use it every where.
I see at least 2 options:
1: declare it as a field and initialize in constructor after InitializeCompoenent()
int number1;
public MyForm()
{
InitializeComponent();
number1 = Convert.ToInt32(numericUpDown1.Value);
}
2: Create a property returning what you want
int number1
{
get { return Convert.ToInt32(numericUpDown1.Value); }
}
I'm brand new to C# and am struggling with a program I am trying to create. I hope I can ask this question to the best of my ability. Per my assignment, we are creating a Windows Form in Visual Basic that creates an account. For the purpose of my question, I have an Account class, a Savings Account class (that is derived from the Account class), I have four forms, I have a AccountForm (that is the main form which displays the account number and the account amount using a string method). I have an estimate interest form, that needs to take the current AccountBalance from the account class (or savings account class, not sure which) and take user entered rate and term (which is collected from the InterestForm) to calculate an estimated interest. Right now, my AccountBalance on my InterestForm is returning 0 and I'm not sure why. Here is my code for the InterestForm.
namespace Assignment_6_third_attempt
{
public partial class InterestForm : Form
{
private SavingsAccount savingsAccount = new SavingsAccount();
//private double accountBalance;
public InterestForm()
{
InitializeComponent();
}
public InterestForm(double accountBalance)
{
accountBalance = savingsAccount.AccountBalance;
InitializeComponent();
}
private void addInterestButton_Click(object sender, EventArgs e)
{
CalculateInterest();
// this.Close();
}
public void CalculateInterest()
{
//A = P(1 + rt)
double accountBalance = savingsAccount.AccountBalance;
double interestRate = double.Parse(interestUpDown.Text);
double term = double.Parse(termUpDown.Text);
double estimateInterest = (accountBalance * (1 + (interestRate * term)));
estimateTextBox.Text = estimateInterest.ToString("C");
}
}
}
Change your InterestForm constructor to:
public InterestForm(double accountBalance) : this()
{
savingsAccount.AccountBalance = accountBalance;
}
class Addition : Form1
{
public string AdditionTotal(){
string AdditionTotal;
int num1 = int.Parse(txtFirstNumber.Text);
int num2 = int.Parse(txtSecondNumber.Text);
AdditionTotal = (num1 + num2).ToString();
return AdditionTotal;
}
public AdditionEqual() //Throws an error here
{
Convert.ToInt32(AdditionTotal);
int AdditionEqual = AdditionTotal;
Addition frm2 = new Addition();
frm2.Show();
this.Hide();
Form 1:
public Form1()
{
InitializeComponent();
}
public string AdditionEqual { get; set; }
private void button1_Click(object sender, EventArgs e)
{
Addition MyLaptop = new Addition();
if (Add.Checked)
{
MessageBox.Show( this.AdditionEqual);
}
Can someone please edit and tell me whats wrong with my code here? I need to use classes and radiobuttons to make a calculator. There's currently 1 error. It says the public AdditionEqual() needs to have a return type. Theres only 1 error but I dont know if the code will actually work after that's fixed. Can someone help?
The function needs a return type. Your first method returns a string:
public string AdditionTotal(){
That string is indicating what datatype the function will return.
public AdditionEqual()
This function doesn't have that indicator. If you don't intend for the method to return anything, use void.
public void AdditionEqual()