Why is my output file printing the payment info backwards? - java

Why does my text file print the code backward? I need it to print the loan balance decreasing from top to bottom. I didn't include the program that will call the methods, let me know if I should post that as well.
Also, if there are any other discrepancies anyone might see, let me know. Thank you!
package amortizationpack;
import java.io.*;
import java.util.Scanner;
import java.lang.Math;
import java.text.DecimalFormat;
public class Amortization {
double loanAmount;
double interestRate;
double loanBalance;
double term;
double payment;
int loanYears;
Scanner keyboard = new Scanner(System.in);
DecimalFormat number = new DecimalFormat("#,##0.00");
public Amortization(double userLoanAmount, int userLoanYears, double userInterestRate) {
loanAmount = userLoanAmount;
loanYears = userLoanYears;
interestRate = userInterestRate;
calcPayment();
} // constructor
public void calcPayment() {
term = (Math.pow((1 + interestRate / 12), (loanYears * 12)));
payment = (loanAmount * (interestRate / 12) * term) / (term - 1);
} // calcPayment method
public int getNumberOfPayments() {
return loanYears * 12;
} // getNumberofPayments
public void saveReport(String loanFile) throws IOException{
double monthlyInterest;
double principal;
File file = new File("LoanReport.txt");
FileWriter fileWrite = new FileWriter(file);
PrintWriter outputFile = new PrintWriter(fileWrite);
outputFile.println("Monthly payment: " + number.format(payment));
outputFile.println("Month\t\t" + "Interest\t\t" + "Principal\t\t"
+ "Balance");
outputFile.println("--------------------------------------------"
+ "-------------------");
for (int m = 1; m <= getNumberOfPayments(); m++) {
monthlyInterest = interestRate / 12.0 * loanBalance;
if (m != getNumberOfPayments()) {
principal = payment - monthlyInterest;
}
else {
principal = loanBalance;
payment = loanBalance + monthlyInterest;
} // for last payment
loanBalance = loanBalance - principal;
outputFile.print(m + "\t\t"
+ number.format(monthlyInterest) + "\t\t" + number.format(principal) + "\t\t"
+ number.format(loanBalance) + "\n");
} // for loop for writing data to text file
outputFile.close();
System.out.print("File Created");
} // saveReport
} // class

I don't see an answer yet, maybe the way you are printing the values along the getNumberOfPayments() value, but correct me if I'm wrong: you are using the loanBalance variable before assigning it a value.

This answer was in the comments so I don't think I could use it as an official answer, credit goes to user16320675.
Basically, I didn't initialize the loanBalance variable, so it was iterating into the negative numbers from zero, instead of decreasing from the starting balance.

Related

UserInput Method keeps assigning a different value in java

this is my first question on the site. I am a fresh CS student needing some help with something that is probably really simple. The code as is will compile. When I enter in the values as the program asks, it stores the values wrong. It will store the right values for gross pay and savings rate but the IRA rate comes back as 100% even when entered at 6.9 and it seems it stores the IRA rate in saveAmount. Please halp me figure out what I am doing wrong here.
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
static Scanner console = new Scanner(System.in);
static DecimalFormat formatCash = new DecimalFormat("#,###.00");
static double iraTotal = 0.0;
static double saveAmount = 0.0;
static double totalSave = 0.0;
static String line = "";
public static void main (String [] args) {
// Input variables
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
String whichOne = ""; // A temp variable to pass a string type into UserInput
printInfo();
grossPay = userInput("gross pay");
saveRate = userInput("savings rate");
iraRate = userInput("IRA rate");
iraTotal = iraAmount(grossPay, iraRate);
saveAmount = savingsAmount(grossPay, saveRate);
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
return;
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public static double iraAmount(double grossPay, double iraRate) {
iraTotal = grossPay * (iraRate / 100.0);
return iraTotal;
} // End iraAmount
public static double savingsAmount(double grossPay, double saveRate) {
saveAmount = grossPay * (saveRate / 100.0);
return saveAmount;
} // End savingsAmount
public static void outputResults(double grossPay, double saveRate, double iraRate,
double saveAmount, double iraTotal) {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of $" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be $" + formatCash.format(saveAmount)
+ ", with a investment amount of $" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of $" +
+ totalSave + ". Way to go for paying yourself!" );
return;
} // End outputResults
} //End Class
Your only issue is the order of arguments you pass to or have set on the outputResults() method.
Change the signature of the method to:
public static void outputResults(double grossPay, double saveRate, double saveAmount, double iraRate, double iraTotal) {
Which now matches how you call the method:
outputResults(grossPay, saveRate, saveAmount, iraRate, iraTotal);
Let me make a couple of additonal suggestions:
1) You are consistently naming arguments in your method signatures the same names as global variables, which makes it confusing which is which when accessing the variable in the method. Either avoid using the same names for the method input variables, or use something like this.amount = amount to make it more obvious of your intention.
2) Avoid static unless you have a valid reason to use it (which is pretty rare).
Instead, take advantage of Java's Object oriented nature and create an instance of your class in the main method and call methods on that instance. This will make your code more readable, reliable, and reusable.
3) In a method that returns type 'void', you don't need to add the empty return; statement.
To correct your issue and also demonstrate the points I listed, I have refactored your code and provided it below. By the way, you have a lot of potential. Despite the fact there are a few details you can improve, for being a first year CS student, your code is well written and thought out. Good job!
import java.text.DecimalFormat;
import java.util.*;
public class CollinDunn_1_05 {
DecimalFormat formatCash = new DecimalFormat("#,###.00");
double iraTotal = 0.0;
double saveAmount = 0.0;
double totalSave = 0.0;
double grossPay = 0.0; // The gross pay from a users paycheck
double saveRate = 0.0; // This is the user entered savings rate
double iraRate= 0.0; // The IRA investment rate
public CollinDunn_1_05(double gross, double saveRt, double iraRt){
this.grossPay = gross;
this.saveRate = saveRt;
this.iraRate = iraRt;
}
public void calculate(){
calcIraAmount();
calcSavingsAmount();
}
public static void main (String [] args) {
Scanner scanner = new Scanner(System.in);
printInfo();
CollinDunn_1_05 program = new CollinDunn_1_05(
userInput("gross pay", scanner),
userInput("savings rate", scanner),
userInput("IRA rate", scanner)
);
program.calculate();
program.outputResults();
} // End Main
public static void printInfo() {
System.out.println ("This program uses methods to calculate \n"
+ "savings amounts and IRA investment amounts \n"
+ "from user input consisiting of their gross pay, \n"
+ "their desired savings rate and IRA rate, made by "
+ " Collin Dunn");
return;
} // End ProgramInfo
public static double userInput(String whichOne, Scanner console) {
double saveMe = 0.0;
System.out.print("Please enter your " + whichOne + ": ");
saveMe = console.nextDouble();
return saveMe;
} // End userInput
public void calcIraAmount() {
iraTotal = grossPay * (iraRate / 100.0);
} // End iraAmount
public void calcSavingsAmount() {
saveAmount = grossPay * (saveRate / 100.0);
} // End savingsAmount
public void outputResults() {
totalSave = saveAmount + iraTotal;
System.out.print ("With a gross pay of \$" + formatCash.format(grossPay)
+ ", a savings rate of %" + formatCash.format(saveRate)
+ " and a IRA rate of %" +formatCash.format(iraRate)
+ ".\n Your savings amount will be \$" + formatCash.format(saveAmount)
+ ", with a investment amount of \$" + formatCash.format(iraTotal)
+ ".\n Which leaves you with a total savings of \$" +
+ totalSave + ". Way to go for paying yourself!" );
} // End outputResults
} //End Class

How to pass a variable between methods without parameters and arguments

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().

have trouble with calling methods. what am i missing?

fix me plz. i get multiple error messages
"variable airSpeed_km might not have been initialized"
"variable width might not have been initialized"
"variable length might not have been initialized"
import java.util.Scanner;
public class V4_________1{
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR;
double airSpeed_km;
double airSpeed_knots;
double width;
double length;
***// need to do something in the main but not sure what exactly***
airSpeed_knots = keyboard.nextDouble();
System.out.println("what is your current airspeed in knots?");
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots, double KNOTS_TO_KMPHR, double airSpeed_km)
{
KNOTS_TO_KMPHR = 1.852;
airSpeed_km = airSpeed_knots * KNOTS_TO_KMPHR ;
return airSpeed_km;
}
public static double calcPatternWidth(double width, double airSpeed_km)
{
width = (airSpeed_km) / (60 * Math.PI) * 2;
return width;
}
public static double calcPatternLength(double airSpeed_km, double length)
{
length = (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
return length;
}
}
You declare:
double airSpeed_km;
And after use it:
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
without any assignment. So you get an error, you can prevent this by giving it a default value of 0 for example.
double airSpeed_km = 0;
(same goes for your other errors)
In Java, the compiler gets upset if a variable even MIGHT be used without a value.
So it is best practice to always give a value to variables when you first declare them.
Since you normally don't know the value a variable will have at the time of declaration, it is common practice to give it a value of zero.
So your declarations should look like this:
double KNOTS_TO_KMPHR=0;
double airSpeed_km=0;
double airSpeed_knots=0;
double width=0;
double length=0;
This will take care of all your "[] might not have been initialized" compiler errors.
Your code is in correct. Your cannot set variable when you pass them into a function. See both approaches and understand what going on.
You can do this:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
System.out.println("your current airspeed in km is: " + getAirSpeed(airSpeed_knots) + "your holding pattern width is: " + calcPatternWidth(getAirSpeed(airSpeed_knots)) + "your holding patter length is: " + calcPatternLength(getAirSpeed(airSpeed_knots));
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}
Or do this if you want to set variables:
public static void main (String args[])
{
Scanner keyboard = new Scanner(System.in);
double KNOTS_TO_KMPHR=1.852;
double airSpeed_knots;
System.out.println("what is your current airspeed in knots?");
airSpeed_knots = keyboard.nextDouble();
double airSpeed_km=getAirSpeed(airSpeed_knots);
double width=calcPatternWidth(airSpeed_km);
double length= calcPatternLength(airSpeed_km);
System.out.println("your current airspeed in km is: " + airSpeed_km + "your holding pattern width is: " + width + "your holding patter length is: " + length);
}
public static double getAirSpeed(double airSpeed_knots)
{
return airSpeed_knots * KNOTS_TO_KMPHR ;
}
public static double calcPatternWidth(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2;
}
public static double calcPatternLength(double airSpeed_km)
{
return (airSpeed_km) / (60 * Math.PI) * 2 + ((airSpeed_km) / 60);
}

Move a method to another method java

import java.util.Scanner;
public class Hw4Part4 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
//Ask for the diners’ satisfaction level using these ratings: 1 = Totally satisfied, 2 = Satisfied,
//3 = Dissatisfied.
System.out.println("Satisfacion leve: ");
int satisfactionNumber= sc.nextInt();
//Ask for the bill subtotal (not including the tip)
System.out.println("What is the bill subtotal: ");
double subtotal= sc.nextInt();
//Report the satisfaction level and bill total.
System.out.println("The satisfaction level is: "+ satisfactionLevel(satisfactionNumber));
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal));
}
public static String satisfactionLevel(int satisfactionNumber){
String satisfactionL = "";
if (satisfactionNumber == 1){
satisfactionL ="Totally-satisfied";
}
if (satisfactionNumber == 2){
satisfactionL = "Satisfied";
}
if (satisfactionNumber == 3){
satisfactionL = "Dissatisfied";
}
return satisfactionL;
}
//This method takes the satisfaction number and returns the percentage of tip to be
//calculated based on the number.
//This method will return a value of 0.20, 0.15, or 0.10
public static double getPercentage(int satisfactionNumber){
double getPercentage = 0;
if (satisfactionNumber ==1){
getPercentage = 0.20;
}
if (satisfactionNumber ==2){
getPercentage = 0.15;
}
if (satisfactionNumber ==3){
getPercentage = 0.10;
}
return getPercentage;
}
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
}
I am having issues on the last method, the whole code is shown above.
It says there is error with the part where I am trying to use the previous method.
I need to get the percentage which was computed on the previous method.
At this part of the code:
public static double getBillTotal(double tipPercentage, double subtotal){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
You call this method:
getPercentage(satisfactionNumber)
However, this variable:
satisfactionNumber
Doesn't exist in this method's scope. You should pass this variable to the method as so:
public static double getBillTotal(double tipPercentage, double subtotal, int satisfactionNumber){
double totalWithTip= (subtotal + ( getPercentage(satisfactionNumber) * subtotal));
return totalWithTip;
}
So when you call the method in the main, you pass it in:
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
tipPercentage cannot be resolved to a varible
Pretty much any variable you pass in, you must create. So when you do the above line, make sure you have all variables delcared:
double tipPercentage, subtotal, satisfactionNumber;
//now set these three variables with a value before passing it to the method
System.out.println("The bill total is: " + getBillTotal(tipPercentage, subtotal, satisfactionNumber));
It's hard to tell, but I think you need to remove whitespace:
double totalWithTip = subtotal + (getPercentage(satisfactionNumber) * subtotal);
return totalWithTip;
This code assumes a variable:
int satisfactionNumber;
and a method:
double getPercentage(int satisfactionNumber) {
// some impl
}

return issue for method

I am having an issue with a method returning to the main method. It is saying that amount in "return amount" cannot be resolved to a variable. Where am I off on this??
This is the message I get:
Multiple markers at this line
- Void methods cannot return a
value
- amount cannot be resolved to a
variable
Here is the code:
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
amount = temp;
System.out.print((count + 1) + " " + temp);
}
{
return amount;
}
}
You curly braces are not correct. The compiler - and me - was confused about that.
This should work (at least syntactically):
import java.util.Scanner;
public class Investment {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years));
}
public static double futureInvestmentValue(
double amount, double interest, int years) {
double monthlyInterest = interest / 1200;
double temp = 0;
double count = 1;
while (count < years)
temp = amount * (Math.pow(1 + monthlyInterest, years * 12));
amount = temp;
System.out.print((count + 1) + " " + temp);
return amount;
}
}
Remove amount from its own scope As a start. Also from the method futureInvestmentValue, you take in amount as an argument but the value is never modified so you're returning the same value being passed which is most likely not the desired outcome.
remove return amount from its own scope
the method futureInvestmentValue... You can't modify any of the parameters inside the method so you have to declare another variable besides amount inside the method (maybe it's the temp variable you keep using) and return that instead
when you return something, the return statement is always inside the method. Never outside it while inside its own braces (never seen this before...)
import java.util.Scanner;
public class Investment {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount invested: ");
double amount = input.nextDouble();
System.out.print("Enter the annual interest rate: ");
double interest = input.nextDouble();
int years = 30;
System.out.print(futureInvestmentValue(amount, interest, years)); //Enter output for table
}
public static double futureInvestmentValue(double amount, double interest, int years) {
double monthlyInterest = interest/1200;
double temp;
double count = 1;
while (count < years) {
temp = amount * (Math.pow(1 + monthlyInterest,years *12));
System.out.print((count + 1) + " " + temp);
}
return amount;
}
}

Categories

Resources