This will be my second question on here; I try not to ask because I don't fancy receiving help for my homework. But I'm just plain stuck.
I'm currently writing a program that stores and updates information for some example bank accounts. My issue is that, somehow, my output has two decimal points.
Example:
"2000.02008.3333333333333"
Side notes: I'm in a Tier II java course, so yes, my code isn't the prettiest. Also, please only offer hints as to where I should make changes. As I said earlier, I try really hard not to ask for help and I don't want my request for help to be misconstrued as cheating. Finally, I do know about syso formatting and will be doing that with the Title information in my driver. The way I did it in there was just faster for me at the time while I fleshed out the rest of the details.
Many thanks in advance to any help provided!
Here's my current code:
public class SavingsAccount
{
private static double annualInterestRate;
private final int ACCOUNT_NUMBER;
private double balance;
public SavingsAccount(int ACCOUNT_NUMBER, double balance)
{
this.ACCOUNT_NUMBER = ACCOUNT_NUMBER;
this.balance = balance;
}
public static double setAnnualInterestRate(double aIR)
{
annualInterestRate = aIR;
return annualInterestRate;
}
public int getAccountNumber()
{
return ACCOUNT_NUMBER;
}
public double getBalance()
{
return balance;
}
public double addMonthlyInterest()
{
balance += (balance * annualInterestRate / 12);
return balance;
}
}
DRIVER
public class Chapter13
{
public static void main(String[] args)
{
double annualInterestRate = .05;
SavingsAccount saver1 = new SavingsAccount(10002, 2000);
SavingsAccount saver2 = new SavingsAccount(10003, 3000);
SavingsAccount.setAnnualInterestRate(annualInterestRate);
System.out.println("Month Acount# Balance Account# Balance");
for(int i = 0; i < 13; i++)
{
System.out.println(i + " " + saver1.getBalance() +
saver1.addMonthlyInterest());
}
}
}
That's because the balance and annualInterestRate are getting printed without any space between them. Add a tab or space between them so that they are printed separately.
System.out.println(i + " " + saver1.getBalance() + "\t" // tab
saver1.addMonthlyInterest());
System.out.println(i + " " + saver1.getBalance() + " " // space
saver1.addMonthlyInterest());
Related
Having trouble compiling these two files to run together.
I get a "can't find or load main class" error or a "erroneous tree" error.
Never asked for help on here before, hope this works :)
package savingsaccount;
import java.util.Scanner;
public class SavingsAccount
{
public static void main(String[] args)
{
double begginingBalance, deposit, withdraw;
int months;
double monthlyRate;
double plus = 0.0;
double minus = 0.0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the balance at beggining of " +
"accounting period.");
begginingBalance = keyboard.nextDouble();
System.out.println("Please enter number of months in current " +
"accounting period.");
months = keyboard.nextInt();
System.out.println("Enter the annual interest rate.");
monthlyRate = keyboard.nextDouble();
a7main accounting = new a7main();
for(int month = 1; month<=months; month++)
{
System.out.println("Enter the amount of deposits for month " +
month + " : ");
plus = keyboard.nextDouble();
accounting.deposits(plus);
System.out.println("Enter the amount of withdrawals for" +
" month " + month + ": ");
minus = keyboard.nextDouble();
accounting.withdrawals(minus);
accounting.interest(monthlyRate);
}
System.out.println("The account balance is: " +
accounting.getBalance());
System.out.println("The total amount of deposits is:" + plus);
System.out.println("The total amount of withdrwals is: " + minus);
System.out.println("The earned interest is: " +
accounting.getRate());
}
}
HERE IS THE CLASS FILE
I am trying to use the methods in this file to calculate and hold the values from the other file.
public class a7main
{
private double totalBalance;
private double interestRate;
public a7main(double balance,double rate)
{
totalBalance = balance;
interestRate = rate;
}
public void deposits(double deposit)
{
totalBalance = totalBalance+deposit;
}
public void withdrawals(double withdraw)
{
totalBalance = totalBalance-withdraw;
}
public void interest(double rate)
{
interestRate = totalBalance*rate;
}
public double getBalance()
{
return totalBalance;
}
public double getRate()
{
return interestRate;
}
}
#Alex Goad -
Add package name in a7main class
You have created parameterized constructor and no default constructor.
a7main accounting = new a7main();
The above line will look for default constructor like
public a7main(){
}
I'm having a problem which I cannot fathom why. I have program I'm making where it takes a few inputs and calculates pay, tax, and final pay.
Everything is working except the final pay.
this calculates the final pay
import java.util.*;
public class Payroll extends Pay
{
public double calc_payroll()
{
super.calc_payroll();
super.tax();
netPay = grossPay - (grossPay * (tax/100));
return netPay;
}
}
this calculates pay and tax
import java.util.*;
public class Pay
{
private float hoursWrkd;
private float rate;
private int hoursStr;
float grossPay;
int tax;
float netPay;
public double calc_payroll()
{
grossPay = getHoursWrkd()*getRate();
return grossPay;
}
public double tax()
{
if (grossPay <= 399.99)
{
tax = 7;
}
else if (grossPay >= 400.00 && grossPay <= 899.99)
{
tax = 11;
}
else if (grossPay <= 900.00)
{
tax = 15;
}
return tax;
}
//Get & Set for hours worked
public float getHoursWrkd()
{
return hoursWrkd;
}
public void setHoursWrkd(float hoursWrkd)
{
this.hoursWrkd = hoursWrkd;
}
//Get & Set for Rate
public float getRate()
{
return rate;
}
public void setRate(float rate) {
this.rate = rate;
}
//Get & Set for hours straight
public int getHoursStr()
{
return hoursStr;
}
public void setHoursStr(int hoursStr)
{
this.hoursStr = hoursStr;
}
}
and this displays all
public class CalPayroll extends Pay
{
public void displayInfo()
{
super.calc_payroll();
super.tax();
Payroll colio = new Payroll();
colio.calc_payroll();
NumberFormat dollars = NumberFormat.getCurrencyInstance();
System.out.println("Gross Pay is : " + dollars.format(grossPay));
System.out.println("Tax is : " + tax + "%");
System.out.println("Net Pay is : " + dollars.format(netPay));
}
i have more files but those are the ones that just take the input, and call the other files.
The math is correct, however when i try to call the netPay variable and format it, it dosn't display any ammount. With grosspay it works. However my teacher said were supposed to pass grosspay into tax so it can use it, im not sure if that would fix it.
PLease help.
You try to display the netPay from CalPayroll, but this class never computes this value. When you do
Payroll colio = new Payroll();
colio.calc_payroll();
You’re probably expecting the netPay to be calculated in CalPayrool, but you’re actually calculating a separate value in a separate object, which has no effect on the current object.
I'm having a bit of an issue with a school project of mine. We're supposed to write a Loan class that will do things associated with, well, loans, such as return the monthly payment and the total payment on the loan. My problem is that I have specific instructions for this code that I absolutely cannot go outside of.
Here's the code:
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Loan
{
public double annualInterestRate = 0;
public int numberOfYears = 0;
public double loanAmount = 0;
public Loan()
{
annualInterestRate = 0.025;
numberOfYears = 1;
loanAmount = 1000;
}
public Loan(double interestRate, int numYears, double amount)
{
setRate(interestRate);
setYears(numYears);
setLoanAmount(amount);
}
public void setRate(double interest)
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
if(interest > 25 || interest < 0)
{
System.out.println("WARNING: Invalid annual interest rate: " + percent.format(interest) + ".");
System.out.println("Current value not changed: " + percent.format(annualInterestRate * 100) + ".");
}
else
{
annualInterestRate = interest;
}
}
public void setYears(int years)
{
if(years > 30 || years <= 0)
{
System.out.println("WARNING: Invalid number of years: " + years + ".");
System.out.println("Current value not changed: " + numberOfYears + ".");
}
else
{
numberOfYears = years;
}
}
public void setLoanAmount(double amnt)
{
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
if(amnt <= 0)
{
System.out.println("WARNING: Invalid loan amount: " + loan.format(amnt) + ".");
System.out.println("Current value not changed: " + loan.format(amnt) + ".");
}
else
{
loanAmount = amnt;
}
}
public double getAnnualInterestRate()
{
return annualInterestRate;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public double getMonthlyPayment()
{
double monthly = annualInterestRate/12;
double monthlyPayment = (loanAmount * monthly)/1 - (1/(1 + monthly));
monthlyPayment = Math.pow(monthlyPayment, 12);
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getmonthlyPayment() * 12;
return totalPayment;
}
public String toString()
{
DecimalFormat percent = new DecimalFormat( "0.0%" );
DecimalFormat loan = new DecimalFormat( "$#,##0.00" );
String interestRate = percent.format(annualInterestRate);
String numOfYears = Integer.toString(numberOfYears);
String loanAmnt = loan.format(loanAmount);
String total = "Annual Interest Rate:\t" + interestRate + "\nNumber of Years:\t\t" + numOfYears + "\nLoan Amount:\t\t\t" + loanAmnt;
return total;
}
}
My problem is with the getTotalPayment method. It can't access the monthlyPayment variable without me either declaring monthlyPayment as a field, like annualInterestRate, or passing it to the getTotalPayment method. The issue is, getTotalPayment is not allowed to have parameters, and we aren't allowed to have any more fields than the three she instructed us to have, which are the three you'll see declared in the beginning of the code.
So, my question: is there a way to make the variable monthlyPayment accessible to getTotalPayment, without making monthlyPayment a field or giving getTotalPayment a parameter?
You have a spelling error in your getTotalPayment() method.
What your trying to do is call the method getmonthlyPayment() when you should be calling getMonthlyPayment().
Incase you missed the suttle difference in my answer you have a lowercase 'm' when you want an uppercase 'M'.
Im not entirety sure if this is your problem, but its the only syntax error my IDE is telling me.
In your revised code you need upper case M in call to getMonthlyPayment().
How do I add the deposit numbers? Do I need some kind of loop (I´m new to JAVA)?.
public class BankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000, "Deposit 1");
account.deposit(2000, "Deposit 2");
System.out.println("Balance: " + account.getBalance());
account.deposit(3000, "Deposit 3");
account.deposit(4000, "Deposit 4");
System.out.println("Balance: " + account.getBalance());
}
private int currentBalance = 0;
private int getBalance() {
int finalBalance = depositAmount + currentBalance;
return finalBalance;
}
private int depositAmount;
public void deposit(int depositAmount) {
this.depositAmount = depositAmount;
}
}
Result should be:
Balance: 3000
Balance: 10000
Your deposit function is suspect. I think you want:
public void deposit(int depositAmount) {
this.currentBalance += depositAmount;
}
Note the +=: this will accumulate the deposit amount. You should also get rid of the class member depositAmount which is also causing bugs. Your getBalance function then reduces to
private/*ToDo - this will probably be public eventually*/ int getBalance() {
return currentBalance;
}
Two more issues though:
This function deposit is not called directly since you are calling a version that also takes a string. (I'm assuming that the function you give is called eventually though).
How will you model decimal values? Don't use a floating point as that will be imprecise. Use a currency type instead.
Well, this might work for you
public class BankAccount {
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.deposit(1000);
account.deposit(2000);
System.out.println("Balance: " + account.getBalance());
account.deposit(3000);
account.deposit(4000);
System.out.println("Balance: " + account.getBalance());
}
private int currentBalance = 0;
private int getBalance() {
return this.currentBalance;
}
public void deposit(int depositAmount) {
this.currentBalance = this.currentBalance + depositAmount;
}
}
You are actually adding everything to the same object account . hence you are getting the result of all values inside it .(i.e) sum of all inputs 10000
I am having some issues with the following syntax.
I am currently learning Java and have been going through a past exam paper to help build my knowledge of Java.
Here is the question:
Write a class Account that has instance variables for the account number and current balance of the account. Implement a constructor and methods getAccountNumber(), getBalance(), debit(double amount) and credit(double amount). In your implementations of debit and credit, check that the specified amount is positive and that an overdraft would not be caused in the debit method. Return false in these cases. Otherwise, update the balance.
I have attempted to do this HOWEVER, I have not implemented the boolean functions for debit and credit methods. I just wanted to build the program first and attempt to get it working. I was going to look at this after as I was not sure how to return true or false whilst also trying to return an amount from the said methods.
Please forgive any errors in my code as I am still learning Java.
I can run my code, but when I enter deposit it does not seem to work correctly and I would appreciate any pointers here please.
Here is my code:
import java.util.*;
public class Account {
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput == withdraw)
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput == deposit)
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}
Again please forgive any errors in my code. I am still learning its syntax.
In the if-statement if(userInput == withdraw) you are attempting to compare String objects.
In Java to compare String objects the equals method is used instead of the comparison operator ==
if(userInput.equals(withdraw))
There are several instances in the code that compares String objects using == change these to use equals.
Also when using conditional blocks it is best to surround the block with braces {}
if(true){
}
You don't use brackets so only the first line after your if-statement gets executed. Also, String's should be compared using .equals(otherString). Like this:
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: "); //Only executed if userInput == withdraw
amount = in.nextDouble(); //Always executed
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
//All executed
}
Do this:
if(userInput.equals(withdraw)) {
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
if (userInput.equals(deposit)) {
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
Note that if your amount to withdraw exceeds your current balance, you will get a 'warning message' but your withdrawal will continue. Thus you'll end up with a negative sum of money. If you don't want to do this, you have to change it accordingly. But, this way it shows how the use of brackets (or not using them) has different effects.
if (userInput == deposit)
should be
if (userInput.equals(deposit))
Same for withdrawal.
On these methods:
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
The inputs to the functions really shouldn't include the current balance, the object already knows what the current balance is (its being held in the objects currentBalance field, which as has been pointed out shouldn't be static).
Imagine a real cash machine that behaved like this:
Whats my current balance:
£100
CreditAccount("I promise my current balance is £1 Million, it really is", £10):
Balance:£1,000,010
Edit: Include code to behave like this
import java.util.*;
public class Account {
private int accountNumber;
private double currentBalance; //balance kept track of internally
// ***** CONSTRUCTOR *****//
public Account(int accountNumber, double currentBalance) {
this.accountNumber = accountNumber;
this.currentBalance = currentBalance;
}
public int getAccountNumber() {
return accountNumber;
}
public double getcurrentBalance() {
return currentBalance;
}
public boolean debit(double amount) {
//we just refer to the objects fields and they are changed
if (currentBalance<amount){
return false; //transaction rejected
}else{
currentBalance -= amount;
return true;
//transaction approaved and occured
}
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public void credit( double amount) {
//credits will always go through, no need for return boolean
currentBalance += amount;
//Note how I directly change currentBalance, there is no need to have it as either an input or an output
}
public static void main(String [] args){
Account acc=new Account(1234,1000);
acc.credit(100);
System.out.println("Current ballance is " + acc.getcurrentBalance());
boolean success=acc.debit(900); //there is enough funds, will succeed
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
success=acc.debit(900); //will fail as not enough funds
System.out.println("Current ballance is " + acc.getcurrentBalance());
System.out.println("Transaction succeeded: " + success);
}
}
I've not bothered using the typed input because you seem to have the hang of that
Without '{' and '}' the first line after an if statement only gets executed as part of that statement. Also, your if (userInput == deposit) block isn't correctly indented, it shouldn't be under the if (userInput == withdraw). And string comparisons should be done using userInput.equals(withdraw)
For the debit and credit methods:
public static boolean debit(double currentBalance, double amount) {
currentBalance -= amount;
if<currentBalance < 0){
return false
}
return true;
}
public static boolean credit(double currentBalance, double amount) {
currentBalance += amount;
if<currentBalance > 0){
return false
}
return true;
}
Now I think I have the boolean values mixed up. The description is a little bit unclear on what to return for each method.
Use equals() method instead == which compares the equality of Objetcs rather values
import java.util.*;
public class Account{
private int accountNumber;
private static double currentBalance;
private static double debit;
// ***** CONSTRUCTOR *****//
public Account(double currentBalance, int accountNumber) {
accountNumber = 12345;
currentBalance = 10000.00;
}
public int getAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
return accountNumber;
}
public double getcurrentBalance(double currentBalance) {
this.currentBalance = currentBalance;
return currentBalance;
}
public static double debit(double currentBalance, double amount) {
currentBalance -= amount;
return currentBalance;
}
public static double credit(double currentBalance, double amount) {
currentBalance += amount;
return currentBalance;
}
public static void main(String [] args){
String withdraw = "Withdraw";
String deposit = "Deposit";
double amount;
Scanner in = new Scanner(System.in);
System.out.println("Are you withdrawing or depositing? ");
String userInput = in.nextLine();
if(userInput.equals(withdraw))
System.out.println("Enter amount to withdraw: ");
amount = in.nextDouble();
if(amount > currentBalance)
System.out.println("You have exceeded your amount.");
debit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
if (userInput .equals(deposit))
System.out.println("Enter amount to deposit: ");
amount = in.nextDouble();
credit(currentBalance, amount);
System.out.println("Your new balance is: " + currentBalance);
}
}