Java - Static Variables - java

If I wanna create a static variable inside this class, which should save the total amount of all accounts. Is this right the way I did it?
Just put a code inside the constructor and good is.
Should anyway only be inside a constructor, right?
How can I print static variables so I am able to check it?
public class Account {
private static double totalBalance = 0;
private final double INTEREST_RATE = 0.015;
private int acctNumber;
private double balance;
private String name;
public Account(String name, int acctNumber, double initialBalance) {
this.name = name;
this.acctNumber = acctNumber;
this.balance = initialBalance;
this.totalBalance += this.balance;
}
public Account(String name, int acctNumber) {
this.name = name;
this.acctNumber = acctNumber;
this.balance = 0.0;
this.totalBalance += this.balance;
}

To much code for simple question. The main thing is keyword static when declaring the field in the class. Always remember that these fields are shared among all instances of the class. In other words, when some instance change the value of the static field it is reflected in the all other instances of that class. Here the simple code is better than the words:
class A {
public static int x;
}
public class Helper {
public static void main(String[] args) {
A someA = new A();
A.x = 0;
A someOtherA = new A();
A.x = 5;
//uncomment next line and see what happens
//someA.x = -55;
System.out.println("x in someA = " + someA.x);
System.out.println("x in someOtherA = " + someOtherA.x);
System.out.println("x in all instances of A = " + A.x);
}
}
EDIT:
About the question can I put the static variable inside the constructor, try this:
class B{
private static int x;
public B(int x){
B.x = x;
}
public int getX() {
return x;
}
}
public class Helper {
public static void main(String[] args) {
B bOne = new B(44);
System.out.println(bOne.getX());
B bTwo = new B(88);
System.out.println(bTwo.getX());
System.out.println(bOne.getX());
}
}
EDIT two
Here is the sample code regarding your questions in the comments:
class Acc {
public static int noOfAccounts;
public static double totalBalance;
public Acc(double balance) {
//increase the number of accounts
Acc.noOfAccounts++;
//add the balance to totalBalance
Acc.totalBalance += balance;
}
}
public class Helper {
//test
public static void main(String[] args) {
Acc aOne = new Acc(15.4);
System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
System.out.println("Acc.totalBalance) = " + Acc.totalBalance);
Acc aTwo = new Acc(100.0);
System.out.println("Acc.noOfAccounts = " + Acc.noOfAccounts);
System.out.println("Acc.totalBalance) = " + Acc.totalBalance);
}
}

Solution summarized:
static variable:
private static double totalBalance;
constructor 1:
totalBalance += this.balance;
others:
totalBalance += amount;
totalBalance -= (amount + fee);
totalBalance += (this.balance * INTEREST_FEE);

Related

How do I compare 2 objects with 1 parameter?

I made a java program that compares the distance between 2 objects
I managed to figure out how to solve it when I make a class with 2 parameters and compare these with the formula seen below;
public class RasterServices {
public static double distance (SimpleRasterElement a, SimpleRasterElement b) {
double d;
d = Math.sqrt(((b.x-a.x)*(b.x-a.x)) + ((b.y-a.y)*(b.y-a.y)));
return d;
}
public class SimpleRasterElement {
public int id;
public double x;
public double y;
public double height;
}
public class SimpleRasterElementTest {
public static void main (String[] args)
{
SimpleRasterElement a, b ; // Deklarera variabeln
a = new SimpleRasterElement (); // Skapa en instans (med ’new’),
b = new SimpleRasterElement ();
// Tilldela variablerna i ’a’ värden:
a.id = 1;
a.x = 6.0;
a.y = 8.0;
a.height = 10.5;
// Tilldela variablerna i ’b’ värden:
b.id = 1;
b.x = 9.0;
b.y = 12.0;
b.height = 15.5;
System.out.println (RasterServices.distance(a,b));
}
}
I can then test this via using my test program RasterServices.distance(a,b)
But now I want to make my variables private, use getters and create the distance() method within the RasterElement-class, and now I'm hardstuck.
public class RasterElementTest {
public static void main(String[] args) {
RasterElement re_a = new RasterElement(1, 6.0, 8.0, 10.5);
RasterElement re_b = new RasterElement(1, 9.0, 12.0, 15.5);
double d = re_a.distance(re_b);
System.out.println(d);
}
}
asd
public class RasterElement {
private final int id;
private final double x;
private final double y;
private final double height;
public RasterElement (int id_nr, double x_val, double y_val, double height_val) {
id = id_nr;
x = x_val;
y = y_val;
height = height_val;
}
public int getId () {
return id;
}
public double getX () {
return x;
}
public double getY () {
return y;
}
public double getHeight () {
return height;
}
public double distance (RasterElement a) {
double d;
d = Math.sqrt(((b.getX()-a.getX())*(b.getX()-a.getX())) + ((b.getY()-a.getY())*b.getY()-a.getY()));
return d;
}
}
But here in distance() i'm only allowed ONE parameter, can someone please explain to me how I can compare two elements/objects when I'm only allowed one parameter in the function?
(By using re_a.distance(re_b); in my test-code)
Thanks, sorry for the long post B-)
(how do I get the b-value into the equation in the method distance in the class RasterElement..?)
Change b to this. Also, you can eliminate d and return directly. Like,
public double distance (RasterElement a) {
return Math.sqrt(((this.getX()-a.getX())*(this.getX()-a.getX()))
+ ((this.getY()-a.getY())*this.getY()-a.getY()));
}

I think I have problem with static methods. How do I fix this error?

public class ConversionTester
{
public static void main(String[] args)
{
double g = gallonsToPints(4.0);
double f = feetToInches(2.0);
System.out.println();
System.out.println();
}
}
public class Conversion
{
public double gallon;
public double feet;
public static double gallonsToPints(double ga)
{
gallon = ga;
return gallon * 8;
}
public static double feetToInches(double fe)
{
feet = fe;
return feet * 12;
}
}
ConversionTester.java: Line 7: You may have forgotten to declare gallonsToPints(double) or it's out of scope.
ConversionTester.java: Line 8: You may have forgotten to declare feetToInches(double) or it's out of scope.
You have two options, either will work. The first is explicitly naming the class like
double g = Conversion.gallonsToPints(4.0);
double f = Conversion.feetToInches(2.0);
The second would be to add static import(s). Before public class ConversionTester like,
static import Conversion.gallonsToPints;
static import Conversion.feetToInches;

Check and correct my code. (I'm a beginner)

Can someone please help me correct my code ? It is created to calculate housing loan (UMI), the coding is correct but it doesn't show the output completely. After "Enter loan duration", it shows a box. Also is there another way to set the variables in class Variables ?
package assignment.pkg2;
import java.util.Scanner;//for Scanner
import java.text.DecimalFormat;//for using decimal format
class Variables{ //set the variables
private double p, r, n;
public void setVarP (double amount){
this.p = amount;
}
public void setVarR (double rate){
this.r = rate;
}
public void setVarN (int duration){
this.n = duration;
}
public double getVarP(){
return p;
}
public double getVarR(){
return r;
}
public double getVarN(){
return n;
}
}
class EMIcalc{ //the calculating part
private double monthlyPay, pow;
Variables var = new Variables();
Scanner scanner = new Scanner(System.in);
public void getPay(){
pow = Math.pow (1+(var.getVarR()/12), - var.getVarN());
monthlyPay = var.getVarP() * ( (var.getVarR()/12) / (1 - pow) );
DecimalFormat Dformat = new DecimalFormat("##.##");
System.out.println(Dformat.format(monthlyPay));
}
}
public class Assignment2 {
public static void main(String[] args) {
Variables var1 = new Variables();
EMIcalc calc = new EMIcalc();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your loan amount");
var1.setVarP(scanner.nextDouble());
System.out.println("Enter interest rate");
var1.setVarR(scanner.nextDouble());
System.out.println("Enter loan duration");
var1.setVarN(scanner.nextInt());
calc.getPay();
}
}
Your are setting the values into var1, but the calc looks at its internal var field, which is a different object. You could just replace var1.set... by calc.var.set....
Or you could merge your Variables and EMIcalc classes into one.
Are you looking for this?
import java.text.DecimalFormat;
import java.util.Scanner;
class Variables { //set the variables
private double p, r, n;
public double getVarP() {
return p;
}
public void setVarP(double amount) {
this.p = amount;
}
public double getVarR() {
return r;
}
public void setVarR(double rate) {
this.r = rate;
}
public double getVarN() {
return n;
}
public void setVarN(int duration) {
this.n = duration;
}
}
class EMIcalc { //the calculating part
Variables var = new Variables();
Scanner scanner = new Scanner(System.in);
private double monthlyPay, pow;
public void getPay() {
pow = Math.pow(1 + (var.getVarR() / 12), -var.getVarN());
monthlyPay = var.getVarP() * ((var.getVarR() / 12) / (1 - pow));
DecimalFormat Dformat = new DecimalFormat("##.##");
System.out.println(Dformat.format(monthlyPay));
}
}
public class Assignment2 {
public static void main(String[] args) {
EMIcalc calc = new EMIcalc();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your loan amount");
calc.var.setVarP(scanner.nextDouble());
System.out.println("Enter interest rate");
calc.var.setVarR(scanner.nextDouble());
System.out.println("Enter loan duration");
calc.var.setVarN(scanner.nextInt());
calc.getPay();
}
}
PS: Try your assignments by yourself.

I am trying to figure out why my class payroll is not adding all the salaries properly....help me find the bug

So I am working on this Payroll class, I need to create two employees, hours worked and hourly pay and the calculate salaries. Finally, I have to add 10 extra hours to one of the previously created employees and calculate and display the total payroll. I wrote the two classes and everything works perfect, but when I look at the total Payroll it does not take into consideration the added hours.
The output for totalPayRoll should be $2000 after increasing the hours but i still get $1750!
public class PayRoll {
static double getTotalPayRoll()
{
return TotalPayRoll;
}
public String employeeId;
public int hoursWorked;
public final double hourlyPay;
private static double TotalPayRoll;
private static double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
Salary = hoursWorked*hourlyPay;
TotalPayRoll = TotalPayRoll + Salary ;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return PayRoll.Salary;
}
public void increase (int extraHours)
{
hoursWorked = (hoursWorked + extraHours);
}
public void changeTheHoursWorked (int amount)
{
hoursWorked = hoursWorked + amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll= TotalPayRoll+Salary;
}
public void changeHours(int newHours)
{
hoursWorked = newHours;
}
}
And this is the main
public class Test {
public static void main(String[] args) {
// TODO code application logic here
Date d = new Date();
DateFormat df = DateFormat.getDateInstance( DateFormat.MEDIUM );
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println("\nPayroll For Week Ending " + df.format(d));
System.out.println("-------------------------------------");
PayRoll employee1 = new PayRoll("444-4444", 30, 25);
employee1.calculateSalary();
displaySalary(employee1, nf);
PayRoll employee2 = new PayRoll("555-5555", 20, 50);
employee2.calculateSalary();
displaySalary(employee2, nf);
System.out.println("Increase " + employee1.getTheEmployeeId() +
" by 10 hours");
employee1.changeTheHoursWorked(10); // 10 hours increase
employee1.calculateSalary();
displaySalary(employee1, nf);
System.out.println("Total payout amount.. " +
nf.format(PayRoll.getTotalPayRoll()));
}
public static void displaySalary(PayRoll e, NumberFormat nf)
{
System.out.println("Employee #: " + e.getTheEmployeeId());
System.out.println("Hours Worked: " + e.getTheHoursWorked());
System.out.println("Hourly Rate: " + e.getTheHourlyPay());
System.out.println("Your Salary is: " + e.getSalary());
System.out.println("---------------------------------\n");
}
}
In your class :
private static double TotalPayRoll;
private static double Salary;
Both are static members(class level members), so there will be only one copy of these members which will be shared among all the objects. Because TotalPayRoll and salary should be different for different payrolls so these should be non-static.
This is because you have static fields - make everything non-static
private static double TotalPayRoll; -> private double TotalPayRoll;
private static double Salary; -> private double Salary;
What is happening with static fields is
Firstly hoursWorked is set to 30
then
hoursWorked is set to 20
then
hoursWorked is increased by 10
Since you are declaring objects of your PayRoll class, you don't need to make an static members.
You can make your class like this
public class PayRoll {
//don't have to declare any member public since you have functions to return value
//don't need access specifier since they are private by default
String employeeId;
int hoursWorked;
double hourlyPay;
double TotalPayRoll=0; //you have to initialize it to zero
double Salary;
public PayRoll (String theEmployeeId, int theHoursWorked,
double theHourlyPay)
{
this.employeeId = theEmployeeId;
this.hoursWorked = theHoursWorked;
this.hourlyPay = theHourlyPay;
// Salary = hoursWorked*hourlyPay;
// TotalPayRoll = TotalPayRoll + Salary ;
//you do not need to do this since you have different functions for them
}
public double getTotalPayRoll()
{
return this.TotalPayRoll;
}
public String getTheEmployeeId()
{
return this.employeeId;
}
public int getTheHoursWorked()
{
return this.hoursWorked;
}
public double getTheHourlyPay()
{
return this.hourlyPay;
}
public double getSalary()
{
return this.Salary;
}
//don't need the increase method
public void changeTheHoursWorked (int amount)
{
hoursWorked += amount;
}
public void calculateSalary()
{
Salary = hoursWorked*hourlyPay;
}
public void calculateTotalPayRoll()
{
TotalPayRoll+=Salary;
}
//don't need the change hours function
}
Hope this helps :)

How can I record previous parameter values and add to new one?

I want to record old values of a parameter and add new parameter values upon the old ones, how can I do this in java?
For example how can I add up the "10" in the auto.fillUp and the "20" in the auto.fillUp?
public class Main {
public static void main(String[] args){
OdometerReading auto = new OdometerReading(15);
auto.fillUp(350, 10);
auto.fillUp(450, 20);
System.out.println("Miles per gallon: " + auto.calculateMPG());
}
}
OdometerReading Class:
public class OdometerReading {
public int myStartMiles;
public int myEndMiles;
public double myGallonsUsed;
public int milesInterval;
public double getMyGallonsUsedNew;
public OdometerReading(int assignedCarMiles){
myStartMiles = assignedCarMiles;
System.out.println("New car odometer reading: " + myStartMiles);
}
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles = milesDriven;
myGallonsUsed = gallonsUsed;
}
public double calculateMPG(){
milesInterval = myEndMiles - myStartMiles;
double mpg = milesInterval / myGallonsUsed;
return mpg;
}
public void reset(){
myStartMiles = myEndMiles;
myGallonsUsed = 0;
}
}
***Note: I am a beginner to Java & programming in general I'm sorry if this may be an "un-professional" question.
Just make the operation in the method, the state gets saved in the object variable and as long as you have a reference to the object you are good.
public void fillUp(int milesDriven, double gallonsUsed){
myEndMiles += milesDriven;
myGallonsUsed += gallonsUsed;
}
Note the + operator

Categories

Resources