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

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.

Related

Java - Static Variables

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);

Bank Account Program Logic Error

I create a very basic bank account program for homework and I keep getting a logic error. Instead of the program giving the total balance after the depositing, withdrawing, and adding interest it just outputs the amount deposited - withdrawn.I appreciate the help, thanks!
public class BankAccount
{
public BankAccount(double initBalance, double initInterest)
{
balance = 0;
interest = 0;
}
public void deposit(double amtDep)
{
balance = balance + amtDep;
}
public void withdraw(double amtWd)
{
balance = balance - amtWd;
}
public void addInterest()
{
balance = balance + balance * interest;
}
public double checkBal()
{
return balance;
}
private double balance;
private double interest;
}
Test Class
public class BankTester
{
public static void main(String[] args)
{
BankAccount account1 = new BankAccount(500, .01);
account1.deposit(100);
account1.withdraw(50);
account1.addInterest();
System.out.println(account1.checkBal());
//Outputs 50 instead of 555.5
}
}
I believe the problem is in your constructor:
public BankAccount(double initBalance, double initInterest)
{
balance = 0; // try balance = initBalance
interest = 0; // try interest = initInterest
}
Change your constructor as
public BankAccount(double initBalance, double initInterest)
{
balance = initBalance;
interest = initInterest;
}
You are not assigning the value you are passing to the constructor to the instance variables
In the constructor you are by default assigning the values as 0 for balance and interest, instead assign the method parameters. Replace the below code
public BankAccount(double initBalance, double initInterest)
{
balance = 0;
interest = 0;
}
public BankAccount(double initBalance, double initInterest)
{
this.balance = initBalance;
this.interest = initInterest;
}

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 :)

My Tester Class in Incomplete and I'm trying to decide if I need to pull methods from my other classes

I am having problems deciding which methods I should pull out of my VendingMachine Class and placed in my TesterClass to test my program. I am attempting to test the VendingMachine and the Candy Classes by constructing Candy objects in my ArrayList but I'm not sure how to best accomplish this. The ArrayList of Candy objects contain the candy bar string and a double price. I want my tester to run the vending machine methods that prompt the user for the questions that are listed in the println methods.
Tester Class
public class Tester {
private static Object candyBarList;
public static void main(String args[])
{
WHAT METHODS SHOULD I PLACE HERE
}
Candy Class
public class Candy{
private double price;
private String candyBarName;
Candy()
{
price = 1.50;
candyBarName = "Pluto Bar";
//default constructor
}
Candy(double price1, String str){
price = price1;
candyBarName = str;
//constructor with parameters
}
public double getPrice(){
return price;
}
public void setPrice(double price){
this.price = price;
}
public String getCandyBarName(){
return candyBarName;
}
public void setCandyBarName(String candyBarName){
this.candyBarName = candyBarName;
}
Vending Machine Class
}
import java.util.ArrayList;
import java.util.Scanner;
import vendingmachine.Candy;
package vendingmachine;
/**
*
* #author admin
*/
public class VendingMachine {
double money = 0.0;
Candy candyBar = new Candy();
ArrayList<Candy> candyBarList = new ArrayList<>();
double cashBox = 0.0;
public VendingMachine(){
candyBarList.add(candyBar);
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
candyBarList.add(new Candy(2.00, "Snickers Bar"));
}
/**
* #return
*/
public double paymentIn(){
Scanner input = new Scanner(System.in);
//double payAmount=0.0;
System.out.println("Insert Money: ");
double payAmount = input.nextDouble();
return payAmount;
}
public static boolean isPaymentEnough(double depositMoney, double price){
if (depositMoney >= price)
{
return true;
}
else{
return false;
}
}
public void dispenseCandy (double depositMoney, Candy selectedCandy){
cashBox+= depositMoney - selectedCandy.getPrice();
candyBarList.remove(selectedCandy);
}
public String candySelector(){
for (int i=0; candyBarList.size() >= i; i++){
System.out.println(candyBarList.get(i));
}
Scanner input = new Scanner(System.in);
String candyBarSelected = input.next();
System.out.println("Please type in the Candy Bar you would like");
candyBarSelected = input.next();
return candyBarSelected;
}
public Candy findCandy(){
String candyName = candySelector();
for (int i=0; candyBarList.size() >= i; i++){
if (candyBarList.get(i).getCandyBarName().equals(candyName)){
return candyBarList.get(i);
}
}
System.out.println("Your selection is invalid");
return null;
}

program cant start, methods withdraw / deposit

im new to methods and classes.
I coded a withdraw/deposit program which ask for name and balance, allowing withdraw and deposit functions. eclipse doesn't allow me to run the program, why is that so?? am I suppose to create (public static void main (string[] args) on a separate class?? and if I have to, what methods(get / set) stay on this class or get transferred to main class?
import java.util.Scanner;
public class bank {
private String name;
private double balance;
private double withdraw;
private double deposit;
private double withdrawTotal;
private double depositTotal;
bank()
{
name = null;
balance = 0;
withdraw = 0;
deposit = 0;
withdrawTotal = 0;
depositTotal = 0;
}
public String getname() {
return name;
}
public double getBalance(){
return balance;
}
//public double getAnnualInterestRate(){
//return annualInterestRate;
//}
public double getWithdraw() {
return withdraw;
}
public double getDeposit() {
return deposit;
}
public double getWithdrawTotal() {
return withdrawTotal;
}
public double getDepositTotal() {
return depositTotal;
}
public void setname(String newname){
Scanner namescan = new Scanner(System.in);
name = namescan.nextLine();
}
public void setBalance(double newBalance){
Scanner bscan = new Scanner(System.in);
balance = bscan.nextInt();
}
public void setWithdraw(double newWithdraw){
withdraw = newWithdraw;
}
public void setDeposit(double newDeposit){
deposit = newDeposit;
}
public void setWithdrawTotal(double newWithdrawTotal){
deposit = newWithdrawTotal;
}
public void setDepositTotal(double newDepositTotal){
deposit = newDepositTotal;
}
//calculate method
public double withdrawCalculuation() {
return balance - withdraw;
}
public double depositCalculation(){
return balance + deposit;
}
//public double annualInterestRateCalculation(){
// return depositTotal * .045;
//}
public void print() {
bank account = new bank();
account.setname(name);
account.setBalance(20000.00);
account.setWithdraw(2500);
account.setWithdrawTotal(17500.00);
account.setDeposit(3000.00);
account.setDepositTotal(20500.00);
//account.setAnnualInterestRate(.045);
System.out.println("The Accound name is:" + account.getname());
System.out.println("The Balance is:" + account.getBalance());
System.out.println("Amount of withdrawal is:" + account.getWithdraw());
System.out.println("The Balance after withdrawal is:" + account.getWithdrawTotal());
System.out.println("Amount of deposit is:" + account.getDeposit());
System.out.println("The Balance after depsoit is:" + account.getDepositTotal());
//System.out.println("The monthly interest for total amount is:" + account.getAnnualInterestRate());
}
}
eclipse doesn't allow me to run the program, why is that so??
Because JVM is not able to find the main() method.
am I suppose to create (public static void main (string[] args) on a separate class??
No. You can add your main() in same class.
Please start with a Basic Java tutorial. You need to have a main method to execute a java program.

Categories

Resources