Java Interests loop with method - java

I have a method which calulates intrests.
public static float calculateIntrests (float Principal, float RateInPercentage){
float result;
result=Principal*RateInPercentage;
return result;
Now I need a loop to print me how much "money" do I have each year. I have done something like this.
import java.util.Scanner;
public class Aplikacija {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int years = 1;
System.out.println("Principal!");
float Principal = input.nextInt();
System.out.println("Rate!");
int Rate = input.nextInt();
float RateInPercentage = Rate / 100.0f;
float calculate = Caluclateintrests(Principal, rateinPercentage);
while (year <= 5) {
System.out.println("It is: " + (calculate) + " dollars in year" + year + "on your account");
year++;
}
input.close();
}
}

Java is a case sensitive, so if you declared variable, method or class with a specific name then you have to sick with the declared name in order to use it,
So you have declared years but you used year instead
int years = 1;
But used as:
while (year <= 5) {//
So here you can do two of thins:
change the declaration of years to be year.
change the using of that variable to years.
This also goes with RateInPercentage variable, Caluclateintrests method.

You have lots and lots of mistakes. Remember to spell it right and that Java is case-sensitive, therefore you have to keep eye on capital letters.
And few mistakes are not syntax, but in logical matter.
Also the naming convention for Java suppose to start naming variables and methods with lower-case letter.
This is working code, try to learn from it :
import java.util.Scanner;
public class Aplikacija {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int year = 1;
System.out.println("Principal!");
float principal = input.nextInt();
System.out.println("Rate!");
int rate = input.nextInt();
float rateInPercentage = rate / 100.0f;
while (year <= 5) {
principal += calculateIntrests(principal, rateInPercentage);
System.out.println("It is: " + principal + " dollars in year" + year + " on your account");
year++;
}
input.close();
}
public static float calculateIntrests(float principal, float rateInPercentage) {
float result;
result = principal * rateInPercentage;
return result;
}
}
Sample output :
Principal!
100
Rate!
1
It is: 101.0 dollars in year1 on your account
It is: 102.01 dollars in year2 on your account
It is: 103.030106 dollars in year3 on your account
It is: 104.06041 dollars in year4 on your account
It is: 105.10101 dollars in year5 on your account

Related

How to set integer range in Scanner? [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 1 year ago.
Improve this question
I am learning java and I want to create a command-line application that calculates exam percentages based on marks obtained. But the problem is I don't have the idea to set the range of marks obtained while the marks range is between 0 to 100.
Below is the code, I have tried: -
package com.company;
import java.util.*;
public class CbseCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of Physics");
float physics = sc.nextFloat();
System.out.println("Enter marks obtained of Chemistry");
float chemistry = sc.nextFloat();
System.out.println("Enter marks obtained of Math");
float math = sc.nextFloat();
System.out.println("Enter marks obtained of English");
float english = sc.nextFloat();
System.out.println("Enter marks obtained of Computer Science");
float computer = sc.nextFloat();
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained/total)*100;
System.out.println("The percentage obtained is: "+percentage);
sc.close();
}
}
It is not a good idea to try to get Scanner to do that1.
Instead, you should use Scanner to read an int and then test the result that it gives you to check that it is in the correct range. Something like this:
int number;
if (myScanner.hasNextInt()) {
number = myScanner.nextInt();
if (number < 0 || number > 100) {
// handle case where the number is out of range
}
} else {
// handle case where the input is not an integer
}
I will leave it to you to figure out how to map the above onto your application's requirements.
1 - The standard Scanner class doesn't provide a method that reads a number in a given range (and rejects numbers outside of that range). You could conceivably extend the Scanner class with this functionality, but it would be difficult. There are simpler solutions.
I would suggest you to write a function to get a valid input as below :-
public int getValidInput(Scanner in, int range) {
while (in.hasNext()) {
if (in.hasNextInt()) {
int val = in.nextInt();
if (val >= 0 && val < range) { // <-- from "0" to "range".
return val;
}
} else {
in.next();
}
}
return -1;
}
This function is ensuring that the input is given as an integer only and it lies in the range o to range. You can change it as per your requirement.
Consider this method:
static int getMark(String course){
int mark = 0;
boolean valid = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter marks obtained of " + course + ": ");
while(valid){
mark = sc.nextInt();
if(mark < 0 || mark > 100){
System.out.println("Mark must be between 0-100");
} else {
valid = true;
}
}
sc.close();
return mark;
}
This way you can get two birds with one stone, leaving the resulting code as this:
public static void main(String[] args){
int physics = getMark("Physics");
int chemistry = getMark("Chemistry");
int math = getMark("Math");
int english = getMark("English");
int computer = getMark("Computer Science");
float total = 500;
float obtained = (physics + chemistry + math + english + computer);
float percentage = (obtained / total) * 100;
System.out.println("The percentage obtained is: " + percentage);
}

Compounding interest calculator

My goal is to create a program that asks the user for an amount, asks for the interest rate per year, month or day, asks for how it will be compounded, then asks for the term in either months, days or years.
It ill then print the future value along with the total interest gained.
This is what I have so far and the numbers are incorrect.
if anyone could help revise this and make it work i would be very grateful.
import java.util.Scanner;
public class Compunding {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double compoundingTerms;
double period = 0;
System.out.println("Enter an amount of money: ");
double amount = sc.nextDouble();
System.out.println("Enter an rate of Interest: ");
double rate = sc.nextDouble();
System.out.println("Enter per years, months, or days: ");
String time = sc.next();
System.out.println("Enter how it will be componded monthly, semi-anually, quarterlly, anually: ");
String compoundRate = sc.next();
System.out.println("Enter the term amount: ");
double term = sc.nextDouble();
System.out.println("Enter the term type (Monthy,Yearly,Daily}: ");
String termType = sc.next();
if (time.equals("years")) {
period = 1;
}
if (time.equals("months")) {
period = 12;
}
if (time.equals("days")) {
period = 365;
}
if (compoundRate.equals("monthly")) {
rate = (rate / 100) / 12;
term = term * 12;
}
if (compoundRate.equals("semi-anually")) {
rate = (rate / 100) / 2;
term = term * 2;
}
if (compoundRate.equals("quarterlly")) {
rate = (rate / 100) / 4;
term = term * 4;
}
if (compoundRate.equals("anually")) {
rate = rate / 100;
term = term * 1;
}
double compoundPayment = 0;
for (int i = 1; i <= term; i++ ) {
if (i % period == 0 ) {
colInterest(amount, rate);
}
compoundPayment = amount * (1.0 + rate);
}
System.out.println("The Final payment will be: " + compoundPayment);
}
public static double colInterest(double valueAmount, double valueInterest) {
return valueAmount * valueInterest;
}
}
So there were a number of issues with the original calculation and what was posted. compoundPayment was set outside the for loop, and only once, so that compounding did not occur. Also, the term type was requested but not used, so every term was assumed to be years. I think it's also just hard to follow the logic of the for loop with the mod (I get it, that when we hit a day on which things are compounded, we give interest), but it's tricky to keep track of the various units (so I went for years, but one could make a case for days and a loop like yours). I did simplify and assume the rate given was annual, but you could make it daily and multiply by 365, or monthly and multiply by 12, or, just make sure your period and days have the same unit.
It's also the case that the choice of Double as opposed to BigDecimal to represent the money is one where I followed you lead and am answering the question asked. I'm not arguing what I'm answering here is the best possible approach (and one could enhance by using Currency as opposed to assuming it's in dollars).
One different approach would be to use exponents to work with repeated multiplications, or, even if not, to simplify the for loop (which allows you to do things like print statements along the way and allow for rounding of currency).
I am not fixing potential enhancements like that there aren't always 365 days in a year or formatting the decimals nicely or checking input more vigorously. I am trying to give a sense of a possible way to go.
One subtlety is the cast to (int) for numPeriods, which will, assuming the other parts worked (and I tested that 364 days compounded annually gave no interest, but 365 did), make sure not to give partial interest for periods not completed.
I hope that helps.
import java.util.Scanner;
public class Compounding {
private Scanner sc;
Compounding() {
sc = new Scanner(System.in);
}
public double getAmount() {
//enhancement: catch number format exceptions, negative numbers, etcetera, and presumbaly use a loop to retry
System.out.println("Enter an amount of money: ");
return sc.nextDouble();
}
//return interest as a rate
public double getInterestRate() {
//enhancement, validate input, catch errors
System.out.println("Enter an annual percent rate of interest: ");
double rate = sc.nextDouble();
return rate / 100;
}
public int getTimesCompoundedPerYear() {
System.out.println("Enter how it will be componded monthly, semi-anually, quarterly, anually: ");
String compoundRate = sc.next();
if (compoundRate.equals("monthly")) {
return 12;
} else if (compoundRate.equals("semi-anually")) {
return 2;
} else if (compoundRate.equals("quarterly")) {
return 4;
} else if (compoundRate.equals("annually")) {
return 1;
} else {
System.out.println("Unrecognized compounding, defaulting to monthly");
return 12;
}
}
//return term amount, units still tbd
//allowing for decimals in case someone says 6.5 years for dsomey=thing compounded more than once a year
public double getTermAmount() {
//enhancement, validate input, catch errors
System.out.println("Enter term amount: ");
return sc.nextDouble();
}
public String getTermUnits() {
System.out.println("Enter the term type (years, months, days): ");
String termType = sc.next();
if (termType.equals("years") || termType.equals("months") || termType.equals("days")) {
return termType;
} else {
System.out.println("Unrecognized time period, defaulting to years.");
return "years";
}
}
public static void main(String[] args) {
Compounding compounding = new Compounding();
double period = 12;
double amount = compounding.getAmount();
double annualRate = compounding.getInterestRate(); //interest rates are always quoted as annual, no need to vary that
int timesCompoundedPerYear = compounding.getTimesCompoundedPerYear();
double term = compounding.getTermAmount();
String termUnits = compounding.getTermUnits();
double ratePerPeriod = annualRate / timesCompoundedPerYear;
double timeInYears = term;
if (termUnits.equals("months")) {
timeInYears /= 12;
} else if (termUnits.equals("days")) {
timeInYears /= 365;
}
int numPeriods = (int) timeInYears * timesCompoundedPerYear;
double compoundPayment = amount * Math.pow(1 + ratePerPeriod, numPeriods);
System.out.println("The Final payment will be: " + compoundPayment);
}
}

Java ROI Compound Calculator

I have been trying to make a program that takes in:
Initial Value (in billions)
Growth Rate / Year (in billions)
Purchase Price (in billions)
And then is able to calculate the number of years it would take to break even on the investment. I have been able to accomplish this with a brute force algorithm.
I was wondering if there was a way to do this more efficiently (in a way that is more similar to standard algebra).
My Code:
import java.util.Scanner;
public class ReturnOnInvestment {
public static double initialValue;
public static double growthRate;
public static double purchasePrice;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(" Return on Investment Calculator ");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.print(" Starting Value (In Billions): ");
initialValue = input.nextDouble();
System.out.print(" Growth Rate (Per Year in Billions): ");
growthRate = input.nextDouble();
System.out.print(" Purchase Price (In Billions): ");
purchasePrice = input.nextDouble();
input.close();
System.out.println("-----------------------------------------");
System.out.println(" ROI Period: " + calculateYears(0) + " Years");
}
public static double calculateMoney(double years) {
if(years < 1) return 0;
return calculateMoney(years - 1) + initialValue + (growthRate * (years - 1));
}
public static double calculateYears(double years) {
if(calculateMoney(years) >= purchasePrice) return Math.round(years * 100) / 100.0;
return calculateYears(years + 0.01);
}
}
Yes - you can use the logarithm function for that.
Given your Java code you can write:
public static double yearsNeeded(double initialValue, double growthRate, double purchasePrice) {
return Math.log(purchasePrice / initialValue) / Math.log(1 + growthRate);
}
with an example:
public static void main(String[] args) {
System.out.println("Years to go from 100 to 150 with a growth rate of 5%: "
+ yearsNeeded(100, .05, 150));
}
Basically you're trying to solve for "years":
initialValue * (1 + growthRate) ^ years = purchasePrice
where ^ means exponentiation.
You can rewrite that to:
(1 + growthRate) ^ years = purchasePrice / initialValue
which turns into:
years = [1 + growthRate] log (purchasePrice / initialValue)
where the base of the log is "1 + growthRate". And a log of another base is the same as the log in any base divided by the log of the base.

Cannot find symbol - method: variable(double)

My program is not close to being finished, but I am stuck because the compiler gives me an error message "cannot find symbol - method years(double)" in the depreciatonTable method the variable years.
-I am sure it is very obvious, but I cannot seem to figure out why the compiler comes up with an error.
import java.util.Scanner;
public class Problem1
{
public static void main(String args[])
{
double AcquisVal, SalvageVal, years;
Scanner scan = new Scanner(System.in);
Problem1 val = new Problem1();
System.out.println("Enter the Acquisition Value: ") ;
AcquisVal = scan.nextDouble();
System.out.println("Enter the Salvage Value: ");
SalvageVal = scan.nextDouble();
System.out.println("Enter the years of useful life(in whole years): ");
years = scan.nextDouble();
if (AcquisVal < 0)
{
System.out.println("Acquisition value cannot be negative");
}
else if (years < 1){
System.out.println("Years of useful life must be greater than zero");
}
else if (SalvageVal < 0){
System.out.println("Salvage value cannot be negative");
}
else
val.depreciationtable(AcquisVal, SalvageVal, years);
}
public double depreciationtable(double years, double AcquisVal, double SalvageVal)
{
double depreciation, fraction, annDepreciation, AccDepreciation, BookValue;
while (years > 0)
{
fraction = years / (years (years + 1)/ 2);
years--;
}
depreciation = (AcquisVal - SalvageVal) * fraction;
return depreciation;
}
}
There is something wrong in your logic at
fraction = years / (years (years + 1)/ 2). The years (years + 1) part is logically wrong.
Also, look at the Java Naming conventions to use correct variable/method names.

Java loan calculator

I'm trying to code a loan calculator. I seem to be having issues. I am trying to get an input from the user and validate the input. I know I am doing it wrong the problem is I'm scratching my head wondering how to do it right.
I get a red line on the d = getDouble(sc, prompt); and the i = getInt(sc, prompt); which I understand I don't have that coded correctly. I'm just unsure how to go about fixing it.
I also have to validate the continue statement which I wasn't to sure the best way to go about that and finally the instructor expects the code to be 80 lines or less which I am right about 80 lines. I guess I'm looking for a better way to do this but being new I'm scratching my head and I'm hoping someone can lend a hand.
As always I really appreciate the help.
import java.util.Scanner;
import java.text.NumberFormat;
public class LoanCalculator
{
public static double getDoubleWithinRange(Scanner sc, String prompt, double min, double max)
{
double d = 0.0;
boolean isValid = false;
while(isValid == false);
{
d = getDouble(sc, prompt);
if (d <= min)
{
System.out.println("Error! Number must be greater tha 0.0");
}
else if (d >= max)
{
System.out.println("Error number must be less than 1000000.0");
}
else
isValid = true;
}
return d;
}
public static int getIntWithinRange(Scanner sc, String prompt, int min, int max)
{
int i = 0;
boolean isvalid = false;
while(isvalid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be more than 0");
else if (i >= max)
System.out.println("Error! Number must be less than 100");
else
isvalid = true;
}
}
public static void main(String[] args)
{
System.out.println("Welcome to the loan calculator");
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
System.out.println("DATA ENTRY");
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0);
double interestRate = getDoubleWithinRange(sc, "Enter yearly interest rate: ", 0, 20);
int years = getIntWithinRange(sc, "Enter number of years: ", 0, 100);
int months = years * 12;
double monthlyPayment = loanAmount * interestRate/
(1 - 1/Math.pow(1 + interestRate, months));
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(3);
System.out.println("RESULST");
System.out.println("Loan Amount" + currency.format(loanAmount));
System.out.println("Yearly interest rate: " + percent.format(interestRate));
System.out.println("Number of years: " + years);
System.out.println("Monthly payment: " + currency.format(monthlyPayment));
System.out.println();
System.out.println("Continue? (y/n): ");
choice =sc.next();
System.out.println();
}
}
}
You haven't made the implementation of your getDouble(Scanner,String) and getInt(Scanner,String) that's why you're getting the red line.
since you already have a scanner, and prompt string change it to this
System.out.print(prompt);
d = sc.nextDouble();
and for the integer
System.out.print(prompt);
i = sc.nextInt();
I think getDouble and getInt are string functions so you would have to get a string first then call those methods. However, since you have a scanner, I assume you want to use that with the nextXXX methods:
Scanner sc = new Scanner (System.in);
double d = sc.nextDouble();
You can use this complete snippet for educational purposes:
import java.util.Scanner;
class Test {
public static void main (String args[]) {
Scanner sc = new Scanner (System.in);
System.out.print("Enter your double: ");
double d = sc.nextDouble();
System.out.print("Enter your integer: ");
int i = sc.nextInt();
System.out.println("You entered: " + d + " and " + i);
}
}
Transcript:
Enter your double: 3.14159
Enter your integer: 42
You entered: 3.14159 and 42
Basically, the process is:
Instantiate a scanner, using the standard input stream.
Use print for your prompts.
Use the scanner nextXXX methods for getting the input values.
A little more assistance here, based on your comments.
In your main function, you have:
double loanAmount = getDoubleWithinRange(sc, "Enter loan amount: ", 0.0, 1000000.0)
and that function has the prototype:
public static double getDoubleWithinRange(
Scanner sc, String prompt, double min, double max)
That means those variables in the prototype will be set to the values from the call. So, to prompt for the information, you could use something like (and this is to replace the d = getDouble(sc, prompt); line):
System.out.print(prompt);
double d = sc.nextDouble();
And there you have it, you've prompted the user and input the double from them. The first line prints out the prompt, the second uses the scanner to get the input from the user.
As an aside, your checks for the minimum and maximum are good but your error messages have hard-coded values of 0 and 100K. I would suggest that you use the parameters to tailor these messages, such as changing:
System.out.println("Error! Number must be greater tha 0.0");
into:
System.out.println("Error! Number must be greater than " + min);
That way, if min or max change in future , your users won't get confused :-)
I'll leave it up to you to do a similar thing for the integer input. It is your homework, after all :-)

Categories

Resources