Program to calculate interest [closed] - java

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 7 years ago.
Improve this question
This program counts first 6 months interest for given amount, it doesn't work where is the mistake?
import java.util.Scanner;
public class BalAfter6Months{
public static void main(String []args){
int counter=1;
double interest,SavBal,total,amount;
Scanner sc = new Scanner (System.in);
System.out.print("Enter the monthly saving amount: ");
amount = sc.nextDouble();
SavBal = amount;
while (counter<7) {
interest = amount * 0.00417;
total = interest + SavBal;
amount = amount + SavBal;
counter++;
}
System.out.print(total);
}
}

This avoids unnecessary variables, and IMO is much simpler.
import java.util.Scanner;
public class BalAfter6Months{
public static void main(String []args){
double interest, balance;
Scanner sc = new Scanner (System.in);
System.out.print("Enter the monthly saving amount: ");
balance = sc.nextDouble();
int count = 1
while (counter < 7) {
interest = balance * 0.00417;
balance += interest
counter++;
}
System.out.print(total);
}
}

You have coded it correctly. You just have to initialize the total variable to avoid the compiler error.
/* Initialize Total Variable */
double interest,SavBal,total = 0,amount;
Input:
100
Output:
102.502

Related

Void methods cannot return a value -Java

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

How to get a program to run with arrays and methods? [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
I am having an issue with my homework assignment. When the program runs it keeps asking the user to enter the dealers twice instead of once, also when try to calculate to total commission it wrong, and also total sales can't get it to run.
Sales
commission
$1 - $5,000
8%
More than $5,000 to $15,000
15%
More than $15,000
20%
Problem:
Write a method to input and return the number of dealers. Perform the appropriate data validation here.
Write a method to gather the required input data. Perform the appropriate data validation here.
Write a method to calculate the commission array.
Write a method to calculate and return total sales for the dealership. Totals sales does not include the commission.
Write a method to calculate and return average sales for the dealership. The average sales value does not include the commission.
Write a method to calculate and return the total commission for the dealership.
Write a method to display the dealer name and amount of sales and the amount of commission for all dealers in a tabular format.
Write a method that accepts the name of a dealer as its parameter and returns the amount of commission for the given dealer. If the given name does not exist, issue an error message.
In your main method, make sure to call your methods to perform the operations. MAKE sure to display all the calculated data returned by your methods. For example, the totals and averages must be displayed, so the answers could be checked. Make output descriptive and provide 2 digits after the decimal point for all monetary values.
public static void main(String[] args) {
// TODO Auto-generated method stub
int d = dealers();
int [] numberDealers = new int [dealers()];
String [] employeeInfo = new String[numberDealers.length];
dealerInfo(employeeInfo.length);
getCommission(d);
//dealerTotalSales(employeeInfo.length);
}
//Method to get number of dealers from user input
public static int dealers() {
Scanner input = new Scanner(System.in); // Scanner for user input
System.out.println("Enter the number of dealears: ");
int numberDealers = input.nextInt();//Read user input
//Check to see if user is in range
//While not in range display error message and ask for input again
while(numberDealers < 0 || numberDealers > 20)
{
System.out.println("Invalid number, Please enter a number dealers
from 0 - 20!");
numberDealers = input.nextInt();
}
return numberDealers; //Return number of Dealers
}
public static void dealerInfo(int dealer) {
Scanner input = new Scanner(System.in); // Scanner for user input
String[] dealersName = new String [dealer];
double[] dealerSales = new double [dealer];
for (int i = 0; i < dealer; i++)
{
System.out.println("\nEnter the name of dealer: ");
dealersName[i] = input.next();
System.out.println("\nEnter the sales for dealer: ");
dealerSales[i] = input.nextDouble();
System.out.println("Name " + "Sales");
System.out.println(dealersName[i] + " " + dealerSales[i]);
}
}
public static void getCommission( int totalSales) {
double commission = 0.0;
double commissionRate ;
if( totalSales >0 && totalSales < 5000) {
commission = 0.10;
//System.out.print(commission);
}else if(totalSales < 15000 ){
commission = 0.15;
//System.out.print(commission);
}else {
commission = 0.20;
//System.out.print(commission);
}
commissionRate = commission + totalSales;
System.out.println("\n"+commissionRate );
}
public static double dealerTotalSales(int[] numDealers)
{
double totalSales = 0.0;
for (int i = 0; i < numDealers.length; i++) {
totalSales = totalSales + numDealers[i];
}
return totalSales;
}
}
The reason its asking you to enter the number of dealers two times is because you are calling the dealers() function twice in your main function. you can solve this by replacing
int [] numberDealers = new int [dealers()];
with
int [] numberDealers = new int [d];

How can I determine why the weekly earnings is not showing the first three times in my program? [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 5 years ago.
Improve this question
The weekly earnings is not showing first 3 times. It's declaring as size of 4. Weekly earnings is calculating 4 times but it's not displaying. Only 4th time it's displaying.
package test;
import java.util.*;
public class test {
public static void main(String[] args) {
String Name[]= new String[4];
double hoursWorked[] =new double[4];
double hourlyPay[] = new double[4];
double WeeklyEarnings[] =new double[4];
GetInfo(Name,hoursWorked,hourlyPay);
WeeklyEarnings[3] = CalculateTotal(hoursWorked,hourlyPay);
DisplayInfo(Name,hoursWorked,hourlyPay,WeeklyEarnings);
}
public static void GetInfo(String Name[], double hoursWorked[], double hourlyPay[])
{
String blank;
Scanner UserIn = new Scanner(System.in);
for(int i=0;i< Name.length;i++)
{
System.out.print("Please enter name #"+(i+1) + ":");
Name[i]= UserIn.nextLine();
do
{
System.out.print("Please enter the number of hours worked:");
hoursWorked[i] = UserIn.nextDouble();
if(hoursWorked[i]<0)
{
System.out.print("Invalid entry !!! Please try again");
}
}while(hoursWorked[i]<0);
System.out.print("Please enter the hourly pay rate: ");
hourlyPay[i]= UserIn.nextDouble();
blank= UserIn.nextLine();
System.out.print("\n");
}
}
public static double CalculateTotal(double hoursWorked[], double hourlyPay[])
{
double[] WeeklyEarnings =new double[4];
for(int i=0;i<hoursWorked.length;i++)
{
WeeklyEarnings[i] = hoursWorked[i] * hourlyPay[i];
}
return WeeklyEarnings[3];
}
public static void DisplayInfo(String Name[], double hoursWorked[], double hourlyPay[], double weeklyEarnings[])
{
System.out.print("\nName\t Hours Worked\t Hourly Pay\t Weekly Earnings");
for(int i=0;i<weeklyEarnings.length;i++)
{
System.out.printf("\n"+ Name[i]+"\t" +hoursWorked[i] +"\t\t" +"$" +hourlyPay[i] +"\t\t" + "$%.2f",weeklyEarnings[i]);
}
}
}
public static double CalculateTotal(double hoursWorked[], double hourlyPay[])
{
double[] WeeklyEarnings =new double[4];
for(int i=0;i<hoursWorked.length;i++)
{
WeeklyEarnings[i] = hoursWorked[i] * hourlyPay[i];
}
return WeeklyEarnings[3];
}
what you are doing here is returing only one element of the array ( the fourth) instead you should return all the array and manipulate it
public static double[] CalculateTotal(double hoursWorked[], double hourlyPay[])
{
double[] WeeklyEarnings =new double[4];
for(int i=0;i<hoursWorked.length;i++)
{
WeeklyEarnings[i] = hoursWorked[i] * hourlyPay[i];
}
return WeeklyEarnings;
}
Change return WeeklyEarnings[3] to return WeeklyEarnings[]
You asked the method to return only the 4th index instead of returning all indexes of the array.

Java, does not register user input at end of do-while loop [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I have this code:
import java.util.*;
public class MyAccount {
public static double balance = 0.0;
public static double deposit(double deposit){
return balance += deposit;
}
//public void setBalance(double balance){
// this.balance = balance;
//}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String redo = "";
do{
System.out.println("What do you want to do today?");
String answer= in.nextLine();
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = in.nextDouble();
deposit(money);
}
System.out.println("Your balance is " + balance);
System.out.println("Anything else(Y or N)?");
redo = in.nextLine().toUpperCase();
} while(redo.equals("Y"));
}
}
The program works just fine up until the end. If I deposit money into it and reach the line "Anything else(Y or N)?" I can not enter anything after; even though I have the redo String there. Though if I don't deposit money, I can enter something for redo and can get the program to loop. How do I fix it so it loops even when I deposit something?
The reason is somewhat tricky. It's because after you call in.nextDouble(), the \n from the user is still in the input stream, such that redo will be equal to an empty String when you call redo = in.nextLine().toUpperCase(). To fix it, add in.nextLine() like so:
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = in.nextDouble();
in.nextLine();
deposit(money);
}
Or another alternative is:
if(answer.equals("deposit")){
System.out.println("How much do you want to deposit?");
double money = Double.parseDouble(in.nextLine());
deposit(money);
}

How do I get my Java program to round? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 7 years ago.
I want my Java program to round numbers off to two decimals. I've been looking at my class materials and I can't find a solution. Here's the code
import java.io.*;
import java.util.*;
public class prog58i
{
public static void main (String[] args)
{
//input
System.out.print("the amount I wish to borrow is? ");
Scanner a = new Scanner(System.in);
double borrow = a.nextDouble();
//Shows amount of money someone wants to borrow
System.out.print("The loan rate I can get is? ");
Scanner b = new Scanner(System.in);
double rate = b.nextDouble();
//Shows loan interest rate
System.out.print("The number of months it will take me to pay of this loan is? ");
Scanner c = new Scanner(System.in);
double months = c.nextDouble();
//Shows months loan will be taken out
//The Math Part
double MP = borrow * (rate/1200) * (Math.pow((1+rate/1200), months)) / (Math.pow((1+rate/1200), months)- 1);
double intrest = (MP * months) - borrow;
double repaid = (MP*months);
//Output
System.out.print( "My monthly payments will be $" +MP +"\n");
System.out.print( "Total Interest Paid is $" +intrest +"\n");
System.out.print( "Total Amount Paid is $" +repaid +"\n");
}
}
I'm more looking for a tutorial or just some advice on how to do it myself.
if you just need to round the output, you can do
System.out.printf("My monthly payments will be $%.2f%n", MP);
System.out.printf("Total Interest Paid is $%.2f%n", intrest);
System.out.printf("Total Amount Paid is $%.2f%n", repaid);

Categories