Java - Output not printing? - java

I'm a beginner to Java, and I'm trying to write a simple Java program that calculates an amount in a savings account based on an initial amount deposited, number of years, and an interest rate. This is my code, which compiles, but does not actually print the amount of money in the account (basically, it completely ignores my second method).
import java.util.*;
class BankAccount {
public static Scanner input = new Scanner(System.in);
public static double dollars;
public static double years;
public static double annualRate;
public static double amountInAcc;
public static void main(String[] args) {
System.out.println("Enter the number of dollars.");
dollars = input.nextDouble();
System.out.println("Enter the number of years.");
years = input.nextDouble();
System.out.println("Enter the annual interest rate.");
annualRate= input.nextDouble();
}
public static void getDouble() {
amountInAcc = (dollars * Math.pow((1 + annualRate), years));
System.out.println("The amount of money in the account is " + amountInAcc);
}
}
I think it is because I don't call the method anywhere, but I'm a bit confused as to how/where I would do that.

Call it once you have received all the required inputs from the Scanner.
// In main
System.out.println("Enter the number of dollars.");
dollars = input.nextDouble();
System.out.println("Enter the number of years.");
years = input.nextDouble();
System.out.println("Enter the annual interest rate.");
annualRate= input.nextDouble();
getDouble(); // Print out the account amount.

The main method is pretty much the entry point for the program to run. To call a static method in java you can just go:
public static void main(String[] args) {
...
BankAccount.getDouble();
...
}
If it wasn't static you have to create an instance of the class. like:
BankAccount account = new BankAccount();
account.getDouble();

Related

Add a second class to the main class for an annual compensation calculator

I tried searching for this answer and found several answers that were similar to what I am looking for, but I can't seem to apply the suggestions provided on unrelated data to my specific program.
I need to take this working code I have created (a program to calculate an employee's annual compensation) and adjust it in a way that shows two classes (per the instructions of my homework assignment). The output given is exactly what I want, I just need help to reorganize the code so there is more than the main class. Is this something I can get help with here?
Here is my working code:
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
double commissionPercentage = 0.06;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
double totalCompensation = (value * commissionPercentage) + salary;
System.out.println("Your annual compensation is: " + "$" + totalCompensation);
}
}
Thanks in advance.
create a class Employee with salary and commissionPercentage as the fields.
In constructor take the salary and commision% of employee and initate the fields.
in this class Employee create a method which will take vavlue as input and will calculate the compensation and return it.
So from main create the instance of Employee class and call the calculateMethod.
I would structure it with these classes:
AnnualCompensationCalculator which will do the computation for you as a utility class, and
AnnualCompensation main class which would be focused on requesting for the user input (and would call the calculator).
Suppose you can move the logic inside new class.
AnnualCompensationCalculator.java
public class AnnualCompensationCalculator{
private static double commissionPercentage = 0.06;
public static double calculateCompensation(double sales ,double salary){
return((sales * commissionPercentage) + salary);
}
}
AnnualCompensation .java
public class AnnualCompensation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//create salary variable and commission percentage variable
double salary = 60000;
//create command output for the user to get directions to enter value
System.out.println("Enter total amount of sales for the year: ");
double value = input.nextDouble();
System.out.println("Your annual compensation is: " + "$" + AnnualCompensationCalculator.calculateCompensation(value,salary));
}
}
Following Object Oriented Programming, I suggest you create a new class Employee that holds the salary and compensation percentage of an employee, which also has a method for calculating the compensation.
Like this:
class Employee {
private double salary;
private double commPercent;
public Employee(double salary, double commPercent) {
this.salary = salary;
this.commPercent = commPercent;
}
public double calculateCompensation(double totalSales) {
return (totalSales * commPercent) + salary;
}
/* Setters & Getters */
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getCommPercent() {
return commPercent;
}
public void setCommPercent(double commPercent) {
this.commPercent = commPercent;
}
}
Then have your main class use this Employee class to do all the work:
public class AnnualCompensation {
public static void main(String[] args) {
//Initialize an Employee object
Employee emp = new Employee(60000, 0.06);
//Create command output for the user to get directions to enter value
System.out.print("Enter total amount of sales for the year: ");
Scanner input = new Scanner(System.in);
double salesAmt = input.nextDouble();
//Calculate the compensation based on the user input then print it
System.out.println("Your annual compensation is: $"
+ emp.calculateCompensation(salesAmt));
}
}

Logic error in Recursive method

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

Why doesn't my code show presentValue?

package presentvalue;
import java.util.Scanner;
public class PresentValue {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
double P; // present value
double F; // future value
double r; // annual interest rate
double n; // number of years
P = presentValue();
F = futureValue();
r = annualInterest();
n = years();
System.exit(0);
}
public static double presentValue()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the presnt value of you savings account?");
return keyboard.nextDouble();
}
public static double futureValue()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("How much do you want in your account in the future?");
return keyboard.nextDouble();
}
public static double annualInterest()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is youe bank's interest rate?");
return keyboard.nextDouble();
}
public static double years()
{
int input;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many years will the money in the bank?");
return keyboard.nextDouble();
}
public static double presentValue(double F, double r)
{
return F/(1+(r * r));
}
public static void show(double presentValue)
{
System.out.println(presentValue);
}
}
The question says write a method presentValue that preforms this calculation. The method should accept the future value, annual interest rate, and number of years as arguments. It should return the present value, which is the amount that you need to deposit today. Demonstrate the method in a program that lets the user experiment with different values for the formula's terms.
Here is the formula P = F/(1+r)^2
You will have to use Math.pow:
public static double presentValue(double future, double intrest, double years)
{
return future / Math.pow(1.0 + intrest, years);
}
Note that I added the amount of years. You stated two years, but I think you really want to have a parameter to specify the number of years, because, otherwise you wouldn't ask the user for an amount of years, right?

loan payment calculator, how to implement multiple methods. Trouble developing method to interact with main method

The idea of this assignment is to have multiple methods interact with each other. I am asking the user for loan amount, interest rate and duration of loan. Then the program is supposed to have one method that calculates the monthly rate, one method that calculates and returns the monthly payment and a method to print the loan statement (amt borrowed,annual interest rate, number of months, and the monthly payment).
I am not receiving any errors in the editor but my program just asks for the three inputs from the user and does not print the loan statement. Any suggestions?
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
I am not sure if some of my code is still redundant.
Since the main method is static and your CalcMonthlyInterestRate references your main method the CalcMonthlyInterestRate must also be static so that the two create a static reference to each other.
At the bottom of your post we see:
}//end main
}//end class
Class Methods referenced by the main method must also be inside its same class as well as being static. Once you start building your own classes and objects this won't always be the case
}//end main
public static double CalcMonthlyInterestRate(double annualInterestRate) {
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}
}//end class
To capture a double using your method just call something like this in your main method:
double answer = CalcMonthlyInterestRate(/*some double variable here*/); //in main
Your method CalcMonthlyInterestRate need to be within your CarLoan class and not outside of it.
That's because you have it like this:
import java.util.Scanner;//instance of scanner class for input from user
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
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();
}
}//end main method
public static double CalcMonthlyInterestRate(double annualInterestRate)
{
double monthlyInterestRate;
monthlyInterestRate = (annualInterestRate/12);
return monthlyInterestRate;
}
There are a couple problems here... One is that //end main method is not really the end of the main method. It's the end of your class. All methods in Java have to be inside a class. Classes represent objects, and Java is "object-oriented". Each method on an object represents a "behavior" of that object. A behavior dangling applied to nothing is (most of the time) meaningless.
The "class, interface, or enum" expected means that where you are currently typing code, you can only put a class, an interface, or an enum. Those are the top level constructs of a Java program (unless you want to get technical with packages, etc...)
Putting the function inside the class (and fixing some code redundancy), we have:
import java.util.Scanner;//instance of scanner class for input from user
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
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();
double monthlyInterestRate = CalcMonthlyInterestRate(annualInterestRate);
System.out.println("Please enter the number of months you have to pay back your loan.");
numberOfMonths = keyboard.nextInt();
} //end main method
public static double CalcMonthlyInterestRate(double annualInterestRate)
{
return annualInterestRate / 12;
} //end monthly interest method
} //end class
Also, methods in Java usually start with a lowercase letter.

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