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
Related
I am sure this is a dumb question but i have been at it for quite a bit.. I am trying to create a java program that calculates compound interest based off a user input of years and amount of money. But i keep getting an error that a void method cannot return a value. So i switch the method to a double because thats what will be returned, but than it tells me that a double method must return a double. Even tho im returning a double in the loop... Please help
import java.text.DecimalFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#.00");
**strong text**
Scanner reader = new Scanner(System.in); //creates scanner
System.out.println("Enter number of years until retirement: "); //asks user to input number of years until retirement
int Years = reader.nextInt();
if (Years <= 0) {
System.out.println("Please enter a valid number"); //if the number of years was invalid, exits the program and asks to enter a valid number
System.exit(0);
}
System.out.println("Enter amount of money able to save annually: "); //asks user how much money they can input
double MoneySaved = reader.nextInt();
reader.close(); //closes scanner
for(int i=0; i < Years; i++)
{
Total = MoneySaved * 1.05;
return Total;
}
System.out.println("You will have $" + df.format(TotalAmount) + " saved up by retirement");
}
}
change your for to this
Double total = 0;
for(int i=0; i < Years; i++) {
total += MoneySaved;
total *= 1.05;
}
System.out.println(total);
Make the method a double and change
double MoneySaved = reader.nextInt();
to
double MoneySaved = reader.nextDouble();
Also I do not see your declaration of 'Total'; make sure that is declared as a double.
First, main Java method must be void and void methods cannot return a value(even compiler tells you that), although you can use a return statement to break execution of the method and return to calling method.
So answering your question, you have to create method that returns double and then just prints it in your main method or do not return anything and just replace
return Total;
with
System.out.println("You will have $" + df.format(Total) + " saved up by retirement");
PS: it looks like you are new to Java, so for a start read some content about Java, for example offical oracle tutorial
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 wanted the user to enter the pay rate and hours worked. If the hours are 40 or below, it is to multiply the pay rate and the hours together. All of that is to happen in one method and the main method is supposed to call this. However, my program does nothing with the values.
package homework6;
import java.util.Scanner;
public class Homework6 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double T1 = getTotalPay(r, h);
}
public static double getTotalPay(double r, int h){
/*If the number of hours is less than or equal to 40, it simply
multiplies them together and returns the result.*/
if (h <= 40) {
return r*h;
}
}
}
Most likely, you simply need to print the returned value:
...
double T1 = getTotalPay(r, h);
System.out.println("Total pay: " + T1);
As a matter of style, Java variables should start with a lower letter. You should change the name T1 to t1 (or, better, to something like totalPay that is more comprehensible).
Just to clarify: the above goes inside your main() method.
If you want to be fancy, you can format the result as currency:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter your pay rate.");
double r = console.nextDouble();
System.out.println("How many hours did you work this week?");
int h = console.nextInt();
double totalPay = getTotalPay(r, h);
System.out.println("Total pay: " +
NumberFormat.getCurrencyInstance().format(totalPay)
);
}
First of all, you need to print this returned value:
System.out.println(T1);
Second of all, your getTotalPay(double r, int h) method must always return something or throw an exception if the return type declared is not void. Right now it only returns something when the condition is satisfied. Did you even get this to compile? This method should look something like this:
public static double getTotalPay(double r, int h){
if (h <= 40){
return r*h;
} else {
return 0;
}
}
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:
A method that accepts two integer parameters and returns their average.
A method that accepts three integer parameters and returns their average.
A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).
I am totally new to Java and programming, this has me completely lost! Here's what I've tried.
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
}
public double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
public double average (int num1, int num2, int num3)
{
return (num1 + num2 + num3) / 3.0;
}
}
The program doesn't go past getting the values from the user. Please help!
You have to actually call your methods.
Just place
Average avg = new Average();
System.out.println("The average is: " + avg.average(numb1, numb2));
at the end of your main method.
Alternatively you can make the methods static:
public static double average (int num1, int num2) {
return (num1 + num2) / 2.0;
}
More info on constructors and static.
It looks like your not actually printing out the results. Try the following.
System.out.print(average(numb1, numb2));
Let's detail what you did there.
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
}
Then your two next methods compute for two or three given integers their average.
The main method is the first method called during your program execution. The jvm will execute everything inside. So it will declare the three doubles, read two values from keyboard and then end.
If you want to compute the average of numb1 & numb2 using your method, you have to create an object Average and call your average method like this
public static void main(String[] args) {
//Create variables numb1, numb2 & numb3
double numb1, numb2, numb3;
System.out.println("Enter two numbers you'd like to be averaged.");
//Read standard input (keyboard)
Scanner keyboard = new Scanner(System.in);
//Retrieve first input as an int
numb1 = keyboard.nextInt();
//Retrieve second input as an int
numb2 = keyboard.nextInt();
//Declare the average value
double average;
//Create an average instance of the class average
Average averageObject = new Average();
//Call your average method
average = averageObject.average(numb1,numb2);
//Print the result
System.out.println("Average is : " + average);
}
Everything in Java is object (read about Object Oriented Programming).
Writing your class "Average" defines how your object is structured. It has attributes (characteristics) and methods (actions). Your Average object has no attributes. However it has two methods (average with two and three numbers) acting on integers.
However your class is just the skeleton of your object. You need to create an object from this skeleton using the keyword new as :
Average averageObject = new Average();
Sincerely
public class Marks {
int roll_no;
int subject1;
int subject2;
int subject3;
public int getRoll_no() {
return roll_no;
}
public void setRoll_no(int roll_no) {
this.roll_no = roll_no;
}
public int getSubject1() {
return subject1;
}
public void setSubject1(int subject1) {
this.subject1 = subject1;
}
public int getSubject2() {
return subject2;
}
public void setSubject2(int subject2) {
this.subject2 = subject2;
}
public int getSubject3() {
return subject3;
}
public void setSubject3(int subject3) {
this.subject3 = subject3;
}
public void getDetails(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the marks of subject1");
this.subject1 = sc.nextInt();
System.out.println("Enter the marks of subject2");
this.subject2 = sc.nextInt();
System.out.println("Enter the marks of subject3");
this.subject3 = sc.nextInt();
System.out.println("Enter the roll number");
this.roll_no = sc.nextInt();
}
public int getAverage(){
int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
return avg;
}
public void printAverage(){
System.out.println("The average is : " + getAverage());
}
public void printRollNum(){
System.out.println("The roll number of the student is: " + getRoll_no());
}
public static void main(String[] args){
Marks[] e1 = new Marks[8];
for(int i=0; i<2; i++) {
System.out.println("Enter the data of student with id:");
e1[i] = new Marks();
e1[i].getDetails();
e1[i].printAverage();
}
System.out.println("Roll number details");
for(int i=0; i<2; i++){
e1[i].printRollNum();
}
}
}
If you'd like your program to find the average you need to include a call to that method in your main method.
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println("The average of " + numb1 + " and " + numb2 + " is " + average(numb1,numb2);
}
you need to call the methods that you have written after you accept the input.
...
System.out.println("Enter two numbers you'd like to be averaged.");
Scanner keyboard = new Scanner(System.in);
numb1 = keyboard.nextInt();
numb2 = keyboard.nextInt();
System.out.println(average (int numb1 , int numb2 ))
...
You probably want to provide a menu of options for the user to select to determine which method to call
System.out.println("Select one option");
System.out.println("1. Enter two numbers you'd like to be averaged.");
System.out.println("2. Enter the 3 numbers you want averaged.");
System.out.println("3. Enter the number Range you want averaged.");
and based on that answer you can determine which method to call
After the access specifier (public) and before the return type (double) place the Java keyword static. You shouldn't worry about what this means right now.
You have to use bitwise operators.
average of int a and b can be calculated as
avg= (a >> 1) + (b >> 1) + (((a & 1) + (b & 1)) >> 1);
The main method will only execute what it is asked to. If you want the average methods to be executed, you will have to create an object, pass the required variable and call the methods from the main method. Write the following lines in the main method after accepting the input.
Average avrg = new Average();
System.out.println("The average is: " + avrg.average(numb1, numb2, numb3));
Write only numb1 and numb2 if you want to average only two numbers.
Ok, I am teaching myself java and I am trying to write a recursive method that can count how many times it is called/used. This is my code so far:
public class FinancialCompany
{
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
double total = Sum(money);
Months();
StdOut.printf("you have reached an amount of $%8.2f", total);
StdOut.println();
}
public static double Sum(double money)
{
double total = (money * 0.01) + money;
if(total >= 1000000)
{
return total;
}
else
{
total =(money * 0.01) + money;
return Sum(total);
}
}
public static int counter = 0;
public static void Months()
{
counter++;
StdOut.println("It should take about " + counter + " month(s) to reach your goal of $1,000,000");
}
}
This is the output:
Enter your monthly investment: 1000 (I chose 1000)
It should take about 1 month(s) to reach your goal of $1,000,000
you have reached an amount of $1007754.58
Every time I run this is prints out final amount but I want it to tell me how many months it took to get there but all it prints out is 1 month. Any help will be greatly appreciated!
**
Completed Code(Thanks to everyone's contributions!)
**
public class FinancialCompany
{
public static int counter = 0;
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
double investment = money;
double total = Sum(money, investment);
StdOut.println("It should take about " + counter + " month(s) to reach your goal of $1,000,000");
}
public static double Sum(double money, double investment)
{
counter++;
double total = (money * 0.01) + money;
if(total >= 1000000)
{
return total;
}
else
{
return Sum(total + investment ,investment);
}
}
}
Zach
Couldn't you just make a global variable like counter outside of the methods?
Sort of like this.
public class testThingy {
public static int counter = 0;
/* main method and other methods here */
}
Just add 1 to counter every time the method is called (within the method you want counted) and it should update the global variable.
Two ways:
1) is to have a variable that exists outside of the method. (If the method lives on an object, you can make it a variable of the object, for example.) At the start of the method, ++variable. Then you can see what value it ends at.
2) is to make the return value, or part of the return value, the number of calls of all of your children. As in:
-If you do not call yourself, return 1.
-If you do call yourself, return the sum of all the return values of all your self-calls (+1 if you also want to count calls of the method part-way through the tree)
Well since you only call Months() once per execution of the application, then counter increments only once! If you want to persist counter between executions of your application, you will have to save the value at the end of the application, and load it in again when you run the application again.
Month() only gets called once in your code, so it sees that counter == 0, then increments that giving counter == 1. This is the value being printed.
So, your counter++ is in the wrong place. It should be inside at the top of the Sum() method. As this is the method being recursively called, this is where the counter should increment.
Now when Month() gets called it will have the proper value.
I believe that this should give you what you are looking for.
public static void main(String[] args)
{
StdOut.println("Enter your monthly investment: ");
double money= StdIn.readDouble();
int months = 0;
while(money < 10000){
money += invest(money);
months++;
}
StdOut.println("It should take about " + String.valueOf(months) + " month(s) to reach your goal of $1,000,000");
StdOut.printf("you have reached an amount of $%8.2f", money);
StdOut.println();
}
private static double invest(double investment){
return (investment + (investement * 0.01));
}