Where do I input values? - java

Java Gurus,
Working on a class assignment and we are given a set of two programs. One calls on another to calculate interest rate, balances, etc for a bank account. What I am having problems with, is figuring out where I am supposed to input the variables we are given to get a successful compile for our program. Below are the two Java files we were given. I made the adjustments to correct all the purposeful errors in the code so everything compiles nicely so far.
public class BankAccount {
private double balance; // Account balance
private double interestRate; // Interest rate
private double interest; // Interest earned
/**
* The constructor initializes the balance
* and interestRate fields with the values
* passed to startBalance and intRate. The
* interest field is assigned to 0.0.
*/
public BankAccount(double startBalance, double intRate) {
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
/**
* The deposit method adds the parameter
* amount to the balance field.
*/
public void deposit(double amount) {
balance += amount;
}
/**
* The withdraw method subtracts the
* parameter amount from the balance
* field.
*/
public void withdraw(double amount) {
balance -= amount;
}
/**
* The addInterest method adds the interest
* for the month to the balance field.
*/
public void addInterest() {
interest = balance * interestRate;
balance += interest;
}
/**
* The getBalance method returns the
* value in the balance field.
*/
public double getBalance() {
return balance;
}
/**
* The getInterest method returns the
* value in the interest field.
*/
public double getInterest() {
return interest;
}
}
Here is the Program2.java which is what we need to compile:
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay " + "into your account.");
account.deposit(pay);
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
// Withdraw some cash from the account.
System.out.print("How much would you like " + "to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned %bodyquot; + formatter.format( account.getInterest() )" +
" in interest.");
System.out.println("Now your balance is %bodyquot; + formatter.format( account.getBalance() ) )");
}
}
What I am required to enter is 500 for Starting Balance, 0.00125 for Monthly Interest Rate (Interest is compounded monthly in the code and pretty sure I know where to put this variable), 1000 Monthly Pay and 900 withdrawl amount. The end result should be $600.75.
Is all of my code there or do I need to declare the value of the variables Starting Balance, Interest Rate, Monthly Pay and Withdrawl Amount?
Please let me know if I am doing something wrong, or if the answer is smack in front of my face and I am just blind today.

Its a copy paste issue in your code.
Change From:
System.out.println("Your current balance is %bodyquot; + formatter.format( account.getBalance() )");
To:
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
Use below mentioned updated code.
import java.text.DecimalFormat; // Needed for 2 decimal place amounts
import java.util.Scanner; // Needed for the Scanner class
public class Program2 {
public static void main(String[] args) {
BankAccount account; // To reference a BankAccount object
double balance, // The account's starting balance
interestRate, // The annual interest rate
pay, // The user's pay
cashNeeded; // The amount of cash to withdraw
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Create an object for dollars and cents
DecimalFormat formatter = new DecimalFormat("#0.00");
// Get the starting balance.
System.out.print("What is your account's " + "starting balance? ");
balance = keyboard.nextDouble();
// Get the monthly interest rate.
System.out.print("What is your monthly interest rate? ");
interestRate = keyboard.nextDouble();
// Create a BankAccount object.
account = new BankAccount(balance, interestRate);
// Get the amount of pay for the month.
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
// Deposit the user's pay into the account.
System.out.println("We will deposit your pay into your account.");
account.deposit(pay);
System.out.println("Your current balance is " + formatter.format( account.getBalance() ));
// Withdraw some cash from the account.
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
// Add the monthly interest to the account.
account.addInterest();
// Display the interest earned and the balance.
System.out.println("This month you have earned " + formatter.format( account.getInterest() ) +
" in interest.");
System.out.println("Now your balance is " + formatter.format( account.getBalance() ) );
}
}

You're going to want to input those values either when you create your BankAccount class in your second program or at runtime. You could try something like this:
BankAccount account = new BankAccount(500, 0.00125)
And then input the rest of the values at runtime, or you could create local variables in Program 2 for everything and then create a new BankAccount using them as parameters.
Hope it helps.

Related

How to use System.out.printf() to display output of number to only two decimal places?

I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);

Not Getting Complete Output on Program in Eclipse

I am getting no errors from Eclipse but my console output is not what it should be. These are the 2 classes I am working on.
First Class
public class BankAccount
{
private double balance;
private double interestRate;
private double interest;
public BankAccount(double startBalance, double intRate)
{
balance = startBalance;
interestRate = intRate;
interest = 0.0;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount)
{
balance -= amount;
}
public void addInterest()
{
interest = balance * interestRate;
balance += interest;
}
public double getBalance()
{
return balance;
}
public double getInterest()
{
return interest;
}
}
Next Class
import java.util.Scanner;
import java.text.DecimalFormat;
public class Program2
{
public static void main(String[] args)
{
BankAccount account;
double balance = 500,
interestRate = 0.00125,
pay = 1000,
cashNeeded = 900;
Scanner keyboard = new Scanner(System.in);
DecimalFormat formatter = new DecimalFormat ("#0.00");
System.out.print("What is your account's starting balance?");
balance = keyboard.nextDouble();
System.out.print("What is your monthly interest rate?");
interestRate = keyboard.nextDouble();
account = new BankAccount(balance, interestRate);
System.out.print("How much were you paid this month? ");
pay = keyboard.nextDouble();
System.out.println("We will deposit your pay into your account.");
account.deposit(pay);
System.out.println("Your current balance is "
+ formatter.format(account.getBalance()));
System.out.print("How much would you like to withdraw? ");
cashNeeded = keyboard.nextDouble();
account.withdraw(cashNeeded);
account.getInterest();
System.out.println("This month you have earned "
+ formatter.format( account.getInterest() )
+ " in interest.");
System.out.println("Now your balance is "
+ formatter.format( account.getBalance()));
}
}
Output which I am Getting:
What is your account's starting balance?
Output I should be getting:
What is your account's starting balance? 500
What is your monthly interest rate? 0.00125
How much were you paid this month? 1000
We will deposit your pay into your account.
Your current balance is 1500.00
How much would you like to withdraw? 900
This month you have earned 0.75 in interest.
Now your balance is 600.75
Scanners wait for input, until you give it information, it won't move on.
It is working totally fine.
I haven't modified anything in your code.
Actually I am thinking when the program is asking you to enter something, at that point you are not giving the input.
Try giving the input for example 500 when it asks What is your account's starting balance?

Java Computing Monthly Payments Loops

I have a question for yall, I am using loops for the following program and I cant understand how to make it so it displays each payment per month,
You are going to write a program which will display the payment schedule for a loan given an interest rate and the number of payments.
Prompt the user for a loan amount, the annual interest rate, number of years to pay off the loan. First, you will calculate the monthly payment using a formula below. Then you will write a loop displaying the monthly payment breakdown: interest amount, principal applied to the loan, and the balance of the loan.
For a 1 year loan (12 monthly payments) for $10,000 at 7%, the payment breakdown looks like the following:
monthly payment = 865.27
payment:1 interest: 58.33 principal: 806.93 balance: 9193.07
HERE IS THE ISSUE ABOVE I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT.
import java.text.NumberFormat;
import java.util.Scanner;
public class MothlyPay {
public static double calculateMonthlyPayment(
int loanAmount, int termInYears, double interestRate) {
// Convert interest rate into a decimal
// eg. 6.5% = 0.065
interestRate /= 100.0;
// Monthly interest rate
// is the yearly rate divided by 12
double monthlyRate = interestRate / 12.0;
// The length of the term in months
// is the number of years times 12
int termInMonths = termInYears * 12;
// Calculate the monthly payment
// Typically this formula is provided so
// we won't go into the details
// The Math.pow() method is used calculate values raised to a power
double monthlyPayment =
(loanAmount*monthlyRate) /
(1-Math.pow(1+monthlyRate, -termInMonths));
return monthlyPayment;
}
public static void main(String[] args) {
// Scanner is a great class for getting
// console input from the user
Scanner scanner = new Scanner(System.in);
// Prompt user for details of loan
System.out.print("Enter loan amount: ");
int loanAmount = scanner.nextInt();
System.out.print("Enter loan term (in years): ");
int termInYears = scanner.nextInt();
System.out.print("Enter interest rate: ");
double interestRate = scanner.nextDouble();
// Display details of loan
double monthlyPayment = calculateMonthlyPayment(loanAmount, termInYears, interestRate);
double totalPayed = 0;
int month = 1;
double loanAmountRemaining;
// NumberFormat is useful for formatting numbers
// In our case we'll use it for
// formatting currency and percentage values
while(totalPayed <= loanAmount){
totalPayed = totalPayed + monthlyPayment;
double totalLoanAmount = loanAmount + interestRate;
loanAmountRemaining = totalLoanAmount - totalPayed;
month ++;
}
if(monthlyPayment > loanAmount)
totalPayed = totalPayed + loanAmountRemaining;
}
// Display details of the loan
//HERE IS THE ISSUE BELOW, I CANT GET IT TO DISPLAY THE AMOUNT OF PAYMENTS FOR (x) MONTHS AND FOR IT TO DISPLAY THE REST OF THE INFO WITH IT FOR THE FOLLOWING VARIABLE LISTED IN THE PRINTF STATEMENT.
System.out.printf("%9s %9s %9s %9s\n", "monthlypayment", "interestRate", "loanAmount", "loanAmountRemaining");
}
//When user put in the loan amount, interest rate, months, It needs display like the picture below.
Right now, you don't have your print statement in any specific method, meaning it won't be called. I would recommend putting it in your main method, and then running a loop to find and print your values.

Savings Account Class + How to turn in?

The problem
Design a SavingsAccount class that stores a savings account’s annual interest rate and balance. The class constructor should accept the amount of the savings account’s starting balance. The class should also have methods for subtracting the amount of a withdrawal, adding the amount of a deposit, and adding the amount of monthly interest to the balance. The monthly interest rate is the annual interest rate divided by twelve. To add the monthly interest to the balance, multiply the monthly interest rate by the balance, and add the result to the balance.
Test the class in a program that calculates the balance of a savings account at the end of a period of time. It should ask the user for the annual interest rate, the starting balance, and the number of months that have passed since the account was established. A loop should then iterate once for every month, performing the following:
Ask the user for the amount deposited into the account during the month. Use the class method to add this amount to the account balance.
Ask the user for the amount withdrawn from the account during the month. Use the class method to subtract this amount from the account balance.
Use the class method to calculate the monthly interest.
After the last iteration, the program should display the ending balance, the total amount of deposits, the total amount of withdrawals, and the total interest earned.
I keep getting one issue in the Main Program on line 22, that if I fix, it messes up a bunch of the code. Anyone know how I could go about fixing this?
import java.text.DecimalFormat;
import java.util.Scanner;
import java.io.*;
public class SavingsAccountMainProgram {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How much money is in the account?: ");
double startingBalance = keyboard.nextDouble();
System.out.print("Enter the annual interest rate:");
double annualInterestRate = keyboard.nextDouble();
SavingsAccountClass savingAccountClass = new SavingsAccountClass();
SavingsAccount savingsAccountClass = savingAccountClass.new SavingsAccount(
startingBalance, annualInterestRate);
System.out.print("How long has the account been opened? ");
double months = keyboard.nextInt();
double montlyDeposit;
double monthlyWithdrawl;
double interestEarned = 0.0;
double totalDeposits = 0;
double totalWithdrawn = 0;
for (int i = 1; i <= months; i++) {
System.out.print("Enter amount deposited for month: " + i + ": ");
montlyDeposit = keyboard.nextDouble();
totalDeposits += montlyDeposit;
savingsAccountClass.deposit(montlyDeposit);
System.out.print("Enter amount withdrawn for " + i + ": ");
monthlyWithdrawl = keyboard.nextDouble();
totalWithdrawn += monthlyWithdrawl;
savingsAccountClass.withdraw(monthlyWithdrawl);
savingsAccountClass.addInterest();
interestEarned += savingsAccountClass.getLastAmountOfInterestEarned();
}
keyboard.close();
DecimalFormat dollar = new DecimalFormat("#,##0.00");
System.out.println("Total deposited: $" + dollar.format(totalDeposits));
System.out.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
System.out.println("Interest earned: $" + dollar.format(interestEarned));
System.out.println("Ending balance: $"
+ dollar.format(savingsAccountClass.getAccountBalance()));
}}
And the other program for this
import java.util.Scanner;
import java.io.*;
public class SavingsAccountClass {
class SavingsAccount {
private double accountBalance;
private double annualInterestRate;
private double lastAmountOfInterestEarned;
public SavingsAccount(double balance, double interestRate) {
accountBalance = balance;
annualInterestRate = interestRate;
lastAmountOfInterestEarned = 0.0;
}
public void withdraw(double withdrawAmount) {
accountBalance -= withdrawAmount;
}
public void deposit(double depositAmount) {
accountBalance += depositAmount;
}
public void addInterest() {
// Get the monthly interest rate.
double monthlyInterestRate = annualInterestRate / 12;
// Calculate the last amount of interest earned.
lastAmountOfInterestEarned = monthlyInterestRate * accountBalance;
// Add the interest to the balance.
accountBalance += lastAmountOfInterestEarned;
}
public double getAccountBalance() {
return accountBalance;
}
public double getAnnualInterestRate() {
return annualInterestRate;
}
public double getLastAmountOfInterestEarned() {
return lastAmountOfInterestEarned;
}
}
}
Also, would anyone know how I could submit a .class file like the teacher has requested?
Not sure why you have SavingsAccount as inner class. For what purpose?
Here I modified what you have shared and I think it answers the problem statement well
main method
public static void main (String arg[]) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How much money is in the account?: ");
double startingBalance = keyboard.nextDouble();
System.out.print("Enter the annual interest rate:");
double annualInterestRate = keyboard.nextDouble();
SavingsAccount savingsAccount = new SavingsAccount(startingBalance, annualInterestRate);
System.out.print("How long has the account been opened? ");
double months = keyboard.nextInt();
double montlyDeposit;
double monthlyWithdrawl;
double interestEarned = 0.0;
double totalDeposits = 0;
double totalWithdrawn = 0;
for (int i = 1; i <= months; i++) {
System.out.print("Enter amount deposited for month: " + i + ": ");
montlyDeposit = keyboard.nextDouble();
totalDeposits += montlyDeposit;
savingsAccount.deposit(montlyDeposit);
System.out.print("Enter amount withdrawn for " + i + ": ");
monthlyWithdrawl = keyboard.nextDouble();
totalWithdrawn += monthlyWithdrawl;
savingsAccount.withdraw(monthlyWithdrawl);
savingsAccount.addInterest();
interestEarned += savingsAccount.getLastAmountOfInterestEarned();
}
keyboard.close();
DecimalFormat dollar = new DecimalFormat("#,##0.00");
System.out.println("Total deposited: $" + dollar.format(totalDeposits));
System.out.println("Total withdrawn: $" + dollar.format(totalWithdrawn));
System.out.println("Interest earned: $" + dollar.format(interestEarned));
System.out.println("Ending balance: $" + dollar.format(savingsAccount.getAccountBalance()));
}
and, removed SavingsAccountClass and made SavingsAccount as the top level class
class SavingsAccount {
.
.
//everything as it is
}

loan calculator that implements multiple methods

I have been working on a program that is a Java loan payment calculator for my comp sci class. The programs requriements are:
ask user for loan amount, annual interest rate, and number of months
call a method to calculate and return the monthly interest rate
call a method to calculate and return the monthly payments
call a method to print a loan statement showing the amount borrowed, annual interest rate, the number of months and the monthly payment.
This is my first time working with multiple methods. I have developed the code so far as shown below. The netbeans editor is not giving me any errors, however, it does not print the statements from my last method. My questions are:
are my methods set up correctly and passing parameters correctly
why won't the statements print at the end
am i capturing my other methods correctly? Do i need to enter variables in the main method and then call them in the final method.
is any of my code redundant?
I am not really sure how to proceed from here.
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
}
*************************************************
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
**************************************************************************************
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
****************************************************************************************
public static void loanStatment (double loanAmount, double annualInterestRate, intnumberOfMonths, double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end main method
}//end main method
Have a look at your main method and you will see that all you are doing is declaring your variables and receiving input. Your other methods that perform the calculations and the loanStatment (sic) method that prints your results are never called.
I would recommend you read up on the basics as you will waste less of your time with very simple errors like this one.
You need to change your main method like shown below.
import java.util.Scanner;
public class CarLoan {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// declare variables for main method
double loanAmount;//double value loan amount
double annualInterestRate;//double value interest rate
int numberOfMonths;//int value for number of months
double monthlyPayment;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the amount of your loan.");
loanAmount = keyboard.nextDouble();
System.out.println("Please enter the annual interest rate as a decimal. Ex. 7.5% = .075");
annualInterestRate = keyboard.nextDouble();
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
System.out.println("Please enter your monthly payment.");
monthlyPayment = keyboard.nextDouble();
System.out.println("Your monthly interest rate is ");
System.out.println(calcMonthlyInterestRate(annualInterestRate));
System.out.println("Your monthly payment is ");
System.out.println(calcMonthlyPayment(calcMonthlyInterestRate(annualInterestRate),loanAmount,numberOfMonths));
loanStatment(loanAmount,annualInterestRate,numberOfMonths,monthlyPayment);
}
public static double calcMonthlyInterestRate(double annualInterestRate){
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}//end method CalcMonthlyInterestRate
public static double calcMonthlyPayment(double monthlyInterestRate, double loanAmount, int numberOfMonths ){
double monthlyPayment;
double calcMonthlyPayment;
calcMonthlyPayment = (monthlyInterestRate*loanAmount)/(1-(1+monthlyInterestRate)-numberOfMonths);
return monthlyPayment = calcMonthlyPayment;
}//end method CalcMonthlyPayment
public static void loanStatment (double loanAmount,
double annualInterestRate,
int numberOfMonths,
double monthlyPayment){
System.out.println("Your loan amount is " +loanAmount);
System.out.println(annualInterestRate);
System.out.println(numberOfMonths);
System.out.println(monthlyPayment);
}
}//end of CarLoan
I would really suggest you read up a little on how main method works in Java.That will be helpful.

Categories