Using methods to calculate account balance - java

I am trying to return a bank balance that takes into account the number of years, the amount in the account and the interest rate. However, when I compile the program, I receive an error on the return statement. When I try putting the return outside the loop, i get another error.
In Loop:
Exercise3.java:35: error: missing return statement
Out of Loop:
Exercise3.java:34: error: cannot find symbol
}return sum;
^
symbol: variable sum
location: class Exercise3
1 error
The code is below
import java.util.Scanner;//import scanner class
public class Exercise3{//Name of prograsm
public static void main(String args[]){ //declare main method
Scanner sc = new Scanner(System.in);//Declare the scanner method
System.out.println("How much in in your account?");//ask user for balance details
double accBalance = sc.nextDouble();//Store balance details
System.out.println("how many years are you saving? "); //ask the user for how many years they will be saveing
double yrSaving = sc.nextDouble();// Amount of years stored
System.out.println("What is the yearly interest rate ?");//ask the user for the interest rate
double rateInterest = sc.nextDouble();//store the interest rate
double results = balanceAccount(accBalance, yrSaving, rateInterest);//invoke the methofd
System.out.println(results); //print thte results of the method
}
////////////////////////////////////////////////////////////////////////////////
//Calculate the balance of the account method
public static double balanceAccount(double accBalance, double yrSaving, double rateInterest){
double rate = rateInterest / 100;
for(int x = 0; x <= yrSaving; x++){
double sum = accBalance*rate;
return sum;
}
}
}

Use this as a body for your method. Your problem was that you were not returning in every scenario. Also your sum logic was faulted.
double rate = rateInterest / 100;
double sum = 0;
for(int x = 0; x <= yrSaving; x++){
sum += accBalance * rate;
}
return sum;

this is how i did it
public static double balanceAccount(double accBalance, double yrSaving, double rateInterest){
double rate = rateInterest / 100;
double sum = 0;
double finishAmt = 0;
sum += accBalance * rate;
finishAmt = sum * yrSaving +(accBalance);
return finishAmt;
}
}

Related

Write a program that prompts the user to enter ten numbers and displays their mean and standard deviation [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
A program that prompts the user to enter ten numbers and displays their mean and standard deviation. The mean and standard deviation of n numbers are computed as follows:
The code that solve the equation
import java.util.Scanner;
public class Exercises5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double [] numbers = new double [10] ;
System.out.print("Enter ten numbers: ");
for (int i = 0; i < 10; i++)
numbers[i] = input.nextDouble();
double mean,deviation;
mean = mean(numbers);
deviation = std(numbers, mean);
System.out.println("The mean is " + mean);
System.out.printf("The standard deviation is %.5f\n", deviation);
}
public static double mean(double numArray[]){
double sum = 0.0;
int length = numArray.length;
for(double num : numArray)
sum += num;
double mean = sum/length;
return mean;
}
public static double std(double numArray[] , double mean{
double standardDeviation = 0.0;
int length = numArray.length;
for(double num: numArray) {
standardDeviation += Math.pow(num - mean, 2);
}
return Math.sqrt(standardDeviation /(length - 1));
}
}
The only issue that I can see is on line 30:
public static double std(double numArray[] , double mean{
It is missing the closing parenthesis after double mean:
public static double std(double numArray[], double mean) {

How to do an array in a loop

I am making an investment calculator.
So I will be doing a math problem and I want to loop it through each array and there will be 12 of them.
So let's say I am going to invest $1000 with a rate return of 4.5%.
So I will need to do 1000 * 0.045 + 1000 = 1,045 that equals one month. Then I need to do 1,045 * 0.045 + 1,045 = 1,092 that would equal the second month and how would I have it go through a loop like that?
Would I use a for loop? or?
This is what I have so far maybe you'll get it better by reading it. But I still need to create a loop that would like the example I gave above.
public class SimpleInvestment {
static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
double [] num = new double [11];
printWelcome();
double investTotal = getInvestAmount();
double rateTotal = getRate();
}
public static void printWelcome()
{
System.out.println("Welcome to the Investment Calulator");
}
public static double getInvestAmount()
{
double amountInvest;
System.out.print("Hou much will you be investing? ");
amountInvest = input.nextDouble();
while (amountInvest <= 0)
{
System.out.println("Amount must be greater than 0. Try again.");
System.out.print("How much will you be investing? ");
amountInvest = input.nextDouble();
}
return amountInvest;
}
public static double getRate()
{
double rate;
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
while (rate < 0 )
{
System.out.println("Rate must be greater than 0. Try again.");
System.out.print("What will be the rate of return?");
rate = input.nextDouble();
}
return rate;
}
public static void calculateInterst( double num[], double investTotal, double rateTotal)
{
double total;
rateTotal = rateTotal / 100;
total = investTotal * rateTotal + investTotal;
}
}
You can use a while or for loop. In this example I used a for loop.
There is documentation in the code to walk you through the logic.
public static void calculateInterest(double num, double investTotal, double rateTotal) {
double total; //keep the total outside loop
rateTotal = rateTotal / 100; //your percent to decimal calculation
total = investTotal * rateTotal + investTotal; //intial calculation
for (int i = 1; i < num; i++) {//for loop starting at 1 because we alreay calculated the first
total += (total * rateTotal);//just calculate the rate of change
}
System.out.println(total);//either output it or return it. Whatever you want to do from here.
}
I hope this helps!
You can use below code:
where months is the investment duration in months,
investment is the amount that is being invested,
rate is the interest rate. e.g. 0.045
public static double calculateTotal(int months, double investment, double rate) {
double total = investment;
for (int i=1; i <= months; i++) {
total = total + (total * rate);
}
return total;
}

How to take the sum of elements from a for loop?

import java.util.Scanner;
class objectDetails {
double w, t, res, amt;
String ob;
void getDetails(int n) {
Scanner get = new Scanner(System.in);
int limit = n;
System.out.println("Enter Object Details\n");
for (int i = 0; i < limit; i++) {
System.out.println("Name of appliance:\n");
ob = get.next();
System.out.println("Enter the amount of watts per hour:\n");
w = get.nextDouble();
System.out.println("Enter the amount of time in hours used:\n");
t = get.nextDouble();
res = (w * t) / 1000;
amt = (res * 4.2);
System.out.println("The amount in ruppes payable=" + amt);
}
}
}
i want the sum of amt from all the iterations in the loop. Add all the amt and display the total amount payable. im new to coding trying to self learn. thank you
Before the loop,
double total = 0;
and then in the loop (after you calculate the amount)
total += amt;
and finally after the loop, something like
System.out.printf("The total is %.2f%n", total);
Assign one global variable and store the value in that variable and at last print the value of that global variable.
thats all

Dividing values from one array by values from a separate array

I am trying to take values from separate arrays and perform divisional math. I have created a method to perform the division, but I keep getting the "bad operand..." error. I have searched and searched, but cannot find resolution. I need to be able to take the values from tripMiles and divide that by the values from gallons.
import java.util.Scanner;
public class Week6Challenge {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int count = 0;
//double miles = 0, gallons = 0;
//Arrays
String[] tripName;
tripName = new String[11];
double[] tripMiles;
tripMiles = new double[11];
double[] tripMPG;
tripMPG = new double [11];
double[] gallons;
gallons = new double [11];
//double miles = 0, gallons = 0;
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
count++;
}//end while
tripMPG[count] = answer(tripMiles, gallons);
System.out.println("Trip Name \t Miles Traveled \t MPG");
int k = 0;
for(k = 0; k < 10; k++){
System.out.println(tripName[k]+ "\t\t" + tripMiles[k] + "\t\t\t" + tripMPG[k]);
}
}
public static double answer(double[] num1, double[] num2){
return (num1/num2);
}
}
You are trying to divide two arrays like:
return (num1/num2);
Which is not valid.
Instead if you need length or sum of two arrays and then divide, you could sum up all the elements and then divide the two values.
You can't divide array like this (num1/num2)
Code snippet of one method how to do division of arraya
public static double answer(double[] num1, double[] num2){
//assumimg both array is of equal length
for (int i=0;i<num1.length;i++){
double result = num1[i]/num2[i];
}
}
As already been mentioned you can't divide arrays to each other, but their elements.
Change your answer function so instead of two arrays of double it takes two double and returns the result:
//num1 & num2 are double, not array
public static double answer(double num1, double num2){
return (num1/num2);
}
Remove tripMPG[count] = answer(tripMiles, gallons); from right after the while loop and instead add the following line at the end of your while loop right before count++;:
tripMPG[count] = answer(tripMiles[count], gallons[count]);
So your while should look like this:
while (count <= 9){//start while
System.out.println("Enter a description of this trip");
tripName[count] = scan.next();
System.out.println("How many miles did you drive?");
tripMiles[count] = scan.nextDouble();
System.out.println("How many gallons of gas did you use on this trip");
gallons[count] = scan.nextDouble();
tripMPG[count] = answer(tripMiles[count], gallons[count]);
count++;
}//end while

Problem Printing From My Method

Merged with Java JOptionPane Output.
I am new to Java and I have been going crazy trying to get this to work.
I have been trying to get this Print Method to work for the last couple of hour but I just can't figure out what is wrong with it. I don't get any errors when I run it. I only want one output box to display after all of the calculations have been made.
I need to ask the user the following information and display the output for the following:
Number of loans to compare
House Price
Down Payment
My Problem: Something is a matter with my math and the output box is displaying more than once.
I greatly appreciate any help I can get with this. Thanks In Advance!
package javamortgagecalculator;
import javax.swing.JOptionPane;
public class JavaMortgageCalculator {
public static void main(String[] args) {
int numberOfLoans;
double sellingPrice;
double downPayment;
double loanAmount;
double annualInterestRate = 0.0;
int numberOfYears = 0;
double[] interestRatesArr;
int[] numberOfYearsArr;
double[] monthlyPayment;
//A. Enter the Number Of Loans to compare and Convert numberOfLoansString to int
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home Convert homeCostString to double
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
loanAmount = sellingPrice - downPayment;
interestRatesArr = new double[numberOfLoans];
numberOfYearsArr = new int[numberOfLoans];
monthlyPayment = new double[numberOfLoans];
int counter = 1;
for (int i = 0; i < numberOfLoans; i++) {
//Enter the Interest Rate
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
annualInterestRate = Double.parseDouble(annualInterestRateString);
interestRatesArr[i] = (annualInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArr[i] = (numberOfYears);
counter++;
}
printArray(numberOfLoans,
sellingPrice,
downPayment,
loanAmount,
annualInterestRate,
numberOfYears,
interestRatesArr,
numberOfYearsArr,
monthlyPayment);
}
//public static void printArray(int numOfLoans, double price, double dwnPayment, double loanAmt, double[] printRate, int[] printYears) {
public static void printArray(int numberOfLoans2,
double sellingPrice2,
double downPayment2,
double loanAmount2,
double annualInterestRate2,
int numberOfYears2,
double[] interestRatesArr2,
int[] numberOfYearsArr2,
double[] monthlyPayment2){
for (int i = 0; i < numberOfLoans2; i++) {
//Calculate monthly payment
double monthlyPayment = loanAmount2 * annualInterestRate2 / (1 - 1 / Math.pow(1 + annualInterestRate2, numberOfYears2 * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int) (monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPayment2[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPayment2[i] * numberOfYears2 * 12;
//Format to keep totalPayment two digits after the decimal point
//totalPayment = (int) (totalPayment * 100) / 100.0;
//totalPaymentArray[i] = (totalPayment);
StringBuilder sb = new StringBuilder();
int n = 0;
for (int x = 0; x < numberOfLoans2; x++) {
if (n == 0) {
sb.append(String.format("%s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %s\t\t %n", "Selling Price", "Down Payment", "Loan Amount", "Rate", "Years", "Payment"));
}
sb.append(String.format("%s\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t\t\t %s\t\t\t\t\t\t %s\t\t\t\t %n", "$" + sellingPrice2, "$" + downPayment2, "$" + loanAmount2, interestRatesArr2[i] + "%", numberOfYearsArr2[i], "$" + monthlyPayment2[i]));
n++;
}
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
}

Categories