I have to create a program in Java that uses a method to compute future investment value with the user putting in the investment amount and interest rate. It has to display in a table and have years 1-30.
I have ONE error that I cannot figure out how to fix. The error is under //Title in the main where I have futureInvestmentValue. The error is telling me that
futureInvestmentValue cannot be resolved to a variable
Here is my code:
import java.util.Scanner;
public class futureInvestmentValue {
public static double futureInvestmentValue(double investmentAmount,
double monthlyInterestRate, int years){
double futureInvestmentValue = 1;
for (years = 1; years <= 30; years++) {
monthlyInterestRate = years/1200;
futureInvestmentValue =
investmentAmount * Math.pow((1+monthlyInterestRate), years*12);
}
return futureInvestmentValue;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//Get investment amount and yearly interest rate from user
Scanner input = new Scanner (System.in);
System.out.print("Enter investment amount, for example 100:" +
"Enter yearly interest rate, for example 5.25:\n");
double investmentAmount = input.nextDouble();
double annualInterestRate = input.nextDouble();
//Title
System.out.print("Years\t" + "\t Future Value");
for (int years = 1; years <= 30; years++) {
System.out.print(years);
System.out.printf("%4d", futureInvestmentValue);
}
System.out.println();
}
}
In your main method, you are referencing the variable instead of the function name...
System.out.printf("%4d", futureInvestmentValue);
The above should be:
System.out.printf("%4d", futureInvestmentValue(investmentAmount, ..... ));
That is what you get, by the way, for giving variables and functions the same name. Don't do it.
Related
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 2 years ago.
I'm trying to figure out why "monthlyPayment" cannot be found when it is within the parameter of the method I called, which is "interest_Total" (I marked it with two asterisks next to it). Below is my code, followed by the error.
import java.util.*;
public class TestCC
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to the payment calculator");
System.out.println("List of options");
System.out.println("MP: To calculate the Monthly Payment for a fix-rate, fix-term loan");
System.out.println("M: To calculat ethe number of Months to pay off a loan witha fixed monthly payment");
System.out.print("Please enter MP or M: ");
String choice = kb.next();
while (!(choice.equals("MP") || choice.equals("M")))
{
System.out.print("Error; Enter MP or M: ");
}
if (choice.equals("MP"))
{
// Loan Amount
System.out.print("Enter loan amount: ");
while (!kb.hasNextDouble())
{
kb.next();
System.out.print("Enter loan amount: ");
}
double loan = 0;
loan = kb.nextDouble();
// Term Amount
System.out.print("Enter term in years: ");
while (!kb.hasNextInt())
{
kb.next();
System.out.print("Enter term in years: ");
}
int years = 0;
years = kb.nextInt();
// Interest Rate
System.out.print("Enter the interest rate: ");
while (!kb.hasNextDouble())
{
kb.next();
System.out.print("Enter the interest rate: ");
}
double interestRate;
interestRate = kb.nextDouble();
// Calling methods Part 1
payment(loan, years, interestRate);
**interest_Total(monthlyPayment, years, loan);**
}
}
public static double payment(double loan, int years, double interestRate)
{
double monthlyPayment = 0;
monthlyPayment = (loan * (interestRate/12))/(1 - (1/(Math.pow((1 + (interestRate/12)),(years * 12)))));
System.out.printf("Monthly Payment: $%.2f", monthlyPayment);
return monthlyPayment;
}
public static double interest_Total(double monthlyPayment, int years, double loan)
{
double totalInterest2 = 0;
totalInterest2 = ((monthlyPayment * years * 12) - loan);
System.out.printf("Total Interest Paid: %.2f", totalInterest2);
return totalInterest2;
}
}
Below is the error I get
TestCC.java:63: error: cannot find symbol
interest_Total(monthlyPayment, years, loan);
^
symbol: variable monthlyPayment
location: class TestCC
1 error
monthlyPayment is the name of a parameter of the interest_Total function. monthlyPayment is a variable in the payment function. But there is nothing by that name in main where you are calling that function from. Perhaps this is what you meant?
double monthlyPayment = payment(loan, years, interestRate);
interest_Total(monthlyPayment, years, loan);
Change this line
payment(loan, years, interestRate);
To this
double monthlyPayment = payment(loan, years, interestRate);
The scope of variable "monthlyPayment" is within the body of the "payment" fuction. In order to use that variable and pass it to "interest_Total", you can do this:
double monthlyPayment = payment(loan, years, interestRate);
interest_Total(monthlyPayment, years, loan);
You can learn more about the scope of variables in java here
You can't share variables between methods, since monthlyPayment is defined in payment it is local to that method. If you want to access the variable in another method you need to specify them as member variables in the class.
You are getting this error because you haven't declared the monthlyPayment variable before using it to pass a function.
Try this:
double monthlyPayment = payment(loans, years, interestRate);
My question is based on returning a Void method on my main method in java the following its my code. Where am I doing wrong?
package practiceq3;
import java.util.Scanner;
public class Practiceq3 {
public void FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
{
System.out.printf("%-5s %s \n", "Years", "Investment Value");
//For loop
int i;
int y;
for(i = 1; i <= Years; i++)
{
for (y = 1; y <= 12; y++)
{
InvestmentAmount += (InvestmentAmount * MontlyInvestmentRate);
System.out.printf("%-5d %2f \n", i , InvestmentAmount);
}
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the Investment Amount: ");
double InvestmentAmount = input.nextDouble();
System.out.print("Enter the Montly investment rate: ");
double MontlyInvestmentRate = input.nextDouble();
System.out.print("Enter the Years: " );
int Years = input.nextInt();
Practiceq3 m = new Practiceq3();
// Compilation error here:
System.out.printf("Investment Value is $%2f", m.FutureInvestmentValue(input.nextDouble(),(input.nextDouble()/1200), Years));
input.close();
}
}
The compilation fails with the error:
Error:(34, 78) java: 'void' type not allowed here
Your method FutureInvestmentValue doesn't return any value, but you are trying to print the (missing) return value from this method:
System.out.printf("Investment Value is $%2f", m.FutureInvestmentValue(...));
Looking over your code, it's not quite clear how exactly should the method FutureInvestmentValue behave - it seems to print the calculated information itself.
Probable solutions would be either:
System.out.println("Investment Value is:");
m.FutureInvestmentValue(...); // Prints the calculated data itself
Leave the System.out.printf line in the main method unchanged and modify the FutureInvestmentValue to return some value instead of printing it.
You'll need to do one of two things: either return the result from your method or instead of return value, print out the method parameter that you used to store the result.
So either change your FutureInvestmentValue method like this:
public double FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
{
// skip other stuff
return InvestmentAmount;
}
or change your main method to something like this:
double value = input.nextDouble();
m.FutureInvestmentValue(value, value/1200, Years);
System.out.printf("Investment Value is $%2f", value);
As mentioned by Alex FutureInvestmentValue method is void and hence you are getting error. If you want to print theinvestmentValue in print statement then change the return type of method to double and return InvestmentAmount variable value.
i managed to answer this question the way the question requested but i also considered what you guys said and at the end i managed to see my mistakes in my code so the following is my answer for the question
import java.util.Scanner;
public class ClassA {
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
ClassB con = new ClassB();//this is the object of the class
System.out.print("Enter the Investment Amount: ");
double investmentAmount = input.nextDouble();
System.out.println();
System.out.print("Enter the Montly investment rate: ");
double montlyInvestmentRate = input.nextDouble();
System.out.println();
System.out.print("Enter the Years: ");
int years = input.nextInt();
System.out.println();
//this is where we call our void method FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
con.FutureInvestmentValue(investmentAmount ,(montlyInvestmentRate/1200), years);
}
}
}
public class ClassB {
public void FutureInvestmentValue(double InvestmentAmount, double MontlyInvestmentRate, int Years)
{
System.out.printf("%-5s %s \n", "Years", "Future Value");
//For loop
int i;
double Fv;
for(i = 1; i <= Years; i++)
{
//Future value formular A=P(1+i/m)^n*m
Fv = (InvestmentAmount * Math.pow(1+MontlyInvestmentRate,i*12));
System.out.printf("%-5d %.2f \n", i , Fv);
}
}
}
I have written this code. The output should calculate the interest of the Bank but it gives 0.0 as output. I have created a class named as Bank and extended it in ICICI class.
import java.util.Scanner;
public class Bank
{
static double rate;
// n = number of years
public double calculateInterest( double PrincipalAmount, double n)
{
double interest;
interest = (PrincipalAmount * n*rate) /100; // interest formula
return interest;
}
public static void main(String[] args)
{
Scanner s1 = new Scanner(System.in);
System.out.print("Enter PrincipalAmount :" );
double PrincipalAmount = s1.nextDouble();
Scanner s2 = new Scanner(System.in);
System.out.print("Enter Number of Years :" );
double n = s2.nextDouble();
ICICI ic;
ic = new ICICI();// new object created of ICICI Class
ic.rate = rate; // object call by reference
System.out.print("Interest of ICICI is " + ic.calculateInterest( PrincipalAmount,n));
}
}
public class ICICI extends Bank
{
double rate = 4;
}
you are doing following:
ic.rate = rate;
and rate is not initialized....
so ic.rate = 0.0;
you should by the way take a look at this:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
What does the 'static' keyword do in a class?
and this
http://www.oracle.com/technetwork/java/codeconventions-135099.html
calculateInterest method is using static rate variable not instance rate , inheritance does not apply on variable , it does not override variable. so default value of static rate will be 0.0 and hence calculateInterest will give 0.0 (because it is double)answer.
You have mistakenly altered the assignment statement:
ic.rate = rate;
Instead, it should be :
rate= ic.rate;
Thanks!
Im trying to write a program that uses a recursive method to calculate how many months it will take to reach a goal of 10 million total invested if the same amount of money(inputted by the user) is invested with a 2 percent interest added each month. The problem is the method is returning counter too early so my "months" output is inaccurate. My guess is that my last else statement is wrong or my counter is placed incorrectly
Heres my code
import java.util.Scanner;
public class MoneyMakerRecursion {
public static int counter = 0;
public static void main(String[] args) {
//Variables declared
Scanner userInput = new Scanner(System.in);
double investment;
//User is prompted for input
System.out.println("Enter your monthly investment: ");
investment = userInput.nextInt();
//Method is called
Sum(investment);
//Results from recursive method output
System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
}
//recursive Method
public static double Sum(double investment) {
counter++;
double total = (investment * 0.02) + investment;
if(total >= 10000000) {return counter;}
else {return Sum(investment+total);}
}
}
Important point you missed is that your monthly investment is same throughout all months. Hence it should be static variable.
Second point you were adding investment to total which was local variable to that method. Which is not a actual investment for month. its a value passed to that function which changes for each month(Consider your code for this statement)
See below working code.
import java.util.Scanner;
public class MoneyMakerRecursion {
public static int counter = 0;
public static double investment = 0;
public static void main(String[] args) {
//Variables declared
Scanner userInput = new Scanner(System.in);
//User is prompted for input
System.out.println("Enter your monthly investment: ");
investment = userInput.nextInt();
//Method is called
Sum(investment);
//Results from recursive method output
System.out.println("It should take " + counter + " month(s) to reach your goal of $10,000,000");
}
//recursive Method
public static double Sum(double totalInvestment) {
counter++;
double total = (totalInvestment* 0.02) + totalInvestment;
if(total >= 10000000) {return counter;}
else {return Sum(total+investment);}
}
}
Result
Enter your monthly investment:
100000
It should take 55 month(s) to reach your goal of $10,000,000
Here is snapshot: here interest is considered annually hence converting 0.02 monthly interest to per year interest it becomes 0.24
Obviously, I'm not looking for all the answers but some direction would be much appreciated.
So I have this program that prompts the user to enter their annual interest rate and savings amount. The program calculates the compound value for 6 months.
I'm having issues calling the new method into the main method to execute the calculations. The main method asks the users for their annual interest rate and the savings amount. It calls the new method, and if all are positive numbers it executes the program. If any are negative it comes up with an error.
I thought I called the method in the last line with calling it but obviously I am wrong. I have tried googling and am having trouble understanding this calling aspect. Any information would be appreciated. I'm new so I'm still working on this programming thing! Not sure why that last curly bracket isn't in the code. Here's the code:
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
public class FifthAssignment {
static double savingAmount = 0.0; // the 2 given static doubles
static double annualInterestRate = 0.0;
int sixthMonth;
public static double compoundValueMethod(double savingAmount, double annualInterestRate, int sixthMonth) {
return sixthMonth; // sixMonth is the compound value
}
{
DecimalFormat formatter = new DecimalFormat(".00");
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 1; i <= 6; i++) {
sixthMonth = (int) ((savingAmount + sixthMonth) * (1 + monthlyInterestRate));
}
}
}
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00"); // bring in the
// decimal
// formatting for
// program
String SA = JOptionPane.showInputDialog("What is your savings amount? "); // Window
// pops
// up
// asking
// for
// your
// savings
// amount.
// As
// a
// string?
savingAmount = Double.parseDouble(SA); // Returns a double given to
// value in string above
String AIR = JOptionPane.showInputDialog("What is the annual interest rate? "); // Window
// pops
// up
// asking
// for
// annual
// interest
// rate.
// String
// as
// above.
annualInterestRate = Double.parseDouble(AIR); // Returns the same as
// savings amount but
// for annual interest
// rate
{
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is "
+ compoundValueMethod(savingAmount, annualInterestRate, 6));
}
}
}
Function Call should have parenthesis
Try This:
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is " + compoundValueMethod(savingAmount,annualInterestRate,6));
Your function should return the computed value, but in your case you are returning 'void', so it should be like this
public static int compoundValueMethod(double savingAmount, double annualInterestRate, int sixthMonth) {
int res = 0;
DecimalFormat formatter = new DecimalFormat(".00");
sixthMonth = 6;
double monthlyInterestRate = annualInterestRate / 12;
if (savingAmount < 0)
if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Both of your values are negative!");
System.exit(0);
}
if (savingAmount < 0) {
JOptionPane.showMessageDialog(null, "Error. Your savings amount is negative!");
}
else if (annualInterestRate < 0) {
JOptionPane.showMessageDialog(null, "Error. Your annual interest rate is negative!");
}
else {
for (int i = 1; i <= 6; i++) {
res = (int) ((savingAmount + res ) * (1 + monthlyInterestRate));
}
}
return res;
}
Based on the current code you have written, the function is not called properly and should look like :
JOptionPane.showMessageDialog(null, "Your total compounded value after 6 months is " + compoundValueMethod(savingAmount,annualInterestRate,6));
If you always want the value of 6 to be passed to your function, then instead of having it as a parameter to the function, you should be better off declaring a static final class variable like this:
private final static int SIXTH_MONTH = 6;
If you want to read the number of months, then yes your function should have that parameter, you should read that parameter just like the other 2 params you are reading and pass it along. And you should remove the line that is assigning the value of 6 to your method parameter.
sixthMonth = 6;
and instead use the value passed in to the function from the main() function