I am brand new to Java and taking a programming course and really stuck on a particular assignment. I am trying to write a program that can compute the interest on the next monthly mortgage payment. The program needs to read the balance and APR from the console. I also need to put a check in place to make sure that the inputs of balance and the interest rate are not negative. We were also given the formula for (Interest = balance x (annualInterestRate / 1200))
UPDATE: I did the calculation and it seems to be working correctly. How would I put the check in place to make sure that the input of balance and interest is not negative?
import java.util.Scanner;
class assignment1{
public static void main(String[] args) {
float r, m;
Scanner s = new Scanner(System.in);
//System.out.println("Enter Monthly Payment and APR");
// txt
System.out.println("Enter Monthly Balance : ");
m = s.nextFloat();
//int balance = s.nextInt();
System.out.print("Enter the Interest Rate : ");
r = s.nextFloat();
//int interest = s.nextInt();
float rm;
rm = (m * (r / 1200));
// Output input by user
System.out.println("Interest on next monthly mortgage payment: " + rm);
//System.out.println("APR: " + interest);
}
}
Check out Arithmetic Operators in Java.
Something along the lines of "Interest = balance x (annualInterestRate / 1200)" would look very similar in Java code.
It would be something like:
int interestOnNextPayment = balance * (interest / 1200);
To verify that the answer is not negative, you'll want to use the comparison operators. These operators are: <, <=, >, and >=. You can learn more about them here.
For your particular example, you'd want to do something like this:
if(balance < 0 || interest < 0) {
System.out.println("Invalid input!");
}
This snippet will first check to see if balance is less than zero, then check to see if interest is less than zero (it works left to right). If either of those expressions are true, then it will run the code inside the if statement.
Related
import java.util.Scanner;
import java.text.DecimalFormat;
import java.lang.Math;
public class Balance2 {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.00");
Scanner input = new Scanner(System.in);
System.out.println("Enter your monthly deposit amount: ");
double value = input.nextDouble();
System.out.println("Enter the annual interest rate: ");
double annualRate = input.nextDouble();
double monthlyRate = annualRate / 1200;
System.out.println("Enter the number of months: ");
int numMonths = input.nextInt();
for (int month = 1;month <= numMonths;month++){
double interest = (value*monthlyRate)/(1-Math.pow(monthlyRate,numMonths));
value += interest;
System.out.println("Balance at end of month " + month + " is " + df.format(value));
}
}
}
The error I'm getting is that whenever it prints value does not update properly and I need it to go from 1008.33 to 8305.91 in month 8 I just figure out what Im doing wrong
Inputs:
Monthly deposit: 1000
Annual interest rate: 10
number of months: 8
Real outcome :end of month 1 is 1008.33, month 8 is 1068.64
expected outcome: end of month 1 is 1008.33, month 8 is 8305.91
I believe the reason this is happening lays somewhere in the formula I have to get the monthly balance.
Basically, you have the formula wrong.
There are two ways to compute the final balance.
The iterative approach. Perform the interest calculations as the bank would
month 0: balance_0 = 1000
month 1: balance_1 = balance_0 + interest on balance_0 + 1000
month 2: balance_2 = balance_1 + interest on balance_1 + 1000
and so on, until you get to month 8
The interest for each month is the balance at the start of the month x the monthly interest rate. (The monthly interest rate is the yearly interest rate / 12)
The algebraic approach. You find the formula for computing interest compounded over a number of months with a monthly deposit. Then plug in the values.
month 8: balance = "some algebraic formula that involves
raising something to the power of something".
(See Wikipedia for the actual formulae. If you are interested.)
What you seem to have done is take a formula with a power term and plugged it into an iteration.
Solution: use the iterative approach but do the monthly interest calculation as I described above.
I'm currently working on a program for my lab class and I am needing help with the output.
The prompt is to write a general code that evaluates a polynomial (ex: 5x^4+3x^3+2x^2). The instructions say that I have to use an array of coefficients in which the size of the array is the inputted degree "n". The user then has to input a value of x then solve the value for each individual polynomial and add it all together.
Here is my code so far:
import java.util.Scanner;
public class GenPol {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String AnsPol = "yes";
while(AnsPol.equals("yes")) {
System.out.println("Please enter the largest degree of polynomial");
int n = in.nextInt();
if((n>0 || n==0)) {
double[] x = new double[n+1];
int arrayLength = x.length;
for(int degreeLength=0; degreeLength<=arrayLength; degreeLength++){
double totalVal=0; //overall accumulator
double indiV =0; //individual accumulator
for(int i=0; i<=arrayLength; arrayLength--) {
System.out.println("Please enter the coefficient for
degree " + arrayLength + ":");
double coefficient = in.nextDouble();
indiV=coefficient;
}
System.out.println("Please enter the value for x: ");
double xVal = in.nextDouble();
double xPowered = Math.pow(xVal, degreeLength);
double indivVal = indiV*xPowered;
x[degreeLength] = indivVal; //store this value into this
element
totalVal += x[degreeLength]; //add the elements together
String XAns = "yes";
while(XAns.equals("yes")) {
System.out.println("The total value is " + totalVal);
System.out.println("Would you like to evaluate another
value of x?");
XAns = in.nextLine();
}
}
} else{
System.out.println("Please enter a degree that's greater than or
equal to 0.");
}
}
}
}
This is the output when I did a test run:
Please enter the largest degree of polynomial
3
Please enter the coefficient for degree 4:
3
Please enter the coefficient for degree 3:
1
Please enter the coefficient for degree 2:
2
Please enter the coefficient for degree 1:
2
Please enter the coefficient for degree 0:
1
Please enter the value for x:
2
The total value is 1.0
Would you like to evaluate another value of x?
Please enter the largest degree of polynomial
Can someone point me to the right direction in terms of my iteration? I'm not entirely sure why my total value keeps outputting 1.0. And also if my loops are properly placed?
Thank you so much!!
First to make things easier for you i'd recommend creating one loop in the main method. have it call getInput(), calc(), displayResults() and do those jobs in those methods. Second what is going on here (n>0 || n==0)? use n>=0 . third... your main problem lies here
for(int i=0; i<=arrayLength; arrayLength--) {
System.out.println("Please enter the coefficient for
degree " + arrayLength + ":");
double coefficient = in.nextDouble();
indiV=coefficient;
}
if you're still unable to figure it out post and get more hints.
I am working on an exercise from a book, the exercise sounds like this:
Drivers are concerned with the mileage their automobiles get. One driver has kept track of several trips by recording the miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each trip. The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all trips up to this point. All averaging calculations should produce floating-point results. Use class Scanner and sentinel-controlled repetition to obtain the data from the user.
Here is my code:
import java.util.Scanner;
public class consumption {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int miles = 0;
int gallons = 0;
int totalGallons = 0;
int totalMiles = 0;
float mpg = 0;
float totalAverage = 0;
System.out.println("Enter number of gallons or enter -1 to finish:");
gallons = in.nextInt();
while(gallons != -1)
{
gallons += totalGallons;
System.out.println("Enter the number of miles driven:");
miles = in.nextInt();
miles += totalMiles;
mpg = ((float)totalMiles/totalGallons);
System.out.printf("Total Miles per Gallon on this trip is %.2f\n", mpg);
System.out.println("Enter number of gallons:");
gallons = in.nextInt();
}
if(totalGallons!=0)
{
totalAverage = (float) totalMiles/totalGallons;
System.out.printf("Total consumption on all trips is %.2f\n", totalAverage);
}
else
System.out.println("You did not enter a valid gallon quantity\n");
}
}
For some reason, after I enter the sentinel (-1), the output shows NaN instead of the float number it should output.
Also, it does not calculate the totalAverage, not even showing NaN
This is the output:
Enter number of gallons or enter -1 to finish: 25
Enter the number of miles driven: 5
Total Miles per Gallon on this trip is NaN
Enter number of gallons: -1
You did not enter a valid gallon quantity
Process finished with exit code 0
Please help me :(
A NaN value typically arises when you divide zero by zero using floating operations. It is short for "not a number" and is used in some contexts where a computation produces a value that is nonsensical.
(NaN does not represent an infinite number! There is a different floating point value for that: INF).
The primitive operations that generate NaN values in Java are:
0.0 / 0.0
±INF / ±INF
0.0 * ±INF and ±INF * 0.0
INF + (-INF) and (-INF) + INF
INF - (INF) and (-INF) - (-INF)
Some java.lang.Math functions can also generate NaN values. For example, Math.sqrt(-1) produces a NaN.
Hint: take a look at where you are doing the calculation of mpg ... and how you are calculating the two values that the expression uses. Look at them carefully. (And check your lecture notes on what += actually does!)
Inside the while loop, you write the statements
gallons += totalGallons;
miles += totalMiles;
but totalGallons is initialized as 0 and its value never changes. The same is for totalMiles. Therefore the calculation for mpg
mpg = (float) totalMiles / totalGallons;
takes the form of
(float) 0/0;
which is infinity. In Java, infinity for float values is represented as Nan : Not a number. So just change the statements to
totalGallons += gallons;
totalMiles += miles;
EDIT
As the others have said, infinity is not Nan. There's a difference between when Java displays INF and when Nan. Refer to this question for more info: Difference between infinity and not-a-number.
Also, check #StephanC's answer on the cases where JAVA produces Nan.
Please help me. Basically the program should Ask the user to input a number representing the initial balance of a savings account. Assign this number to a double variable called balance.
Ask for a number representing the yearly rate of interest (in percent) on the account. Divide this number by 100.0 and assign it to a double variable called rate. I have to use a loop to update the balance as it changes year by year. I am stuck on that part. Here is the code I have so far :
public static void calcInterest(){
System.out.println("Please enter the account balance : ");
System.out.println("Please enter the annual interest rate : ");
System.out.println("Please enter the number of years : ");
Scanner input = new Scanner (System.in);
double balance = input.nextDouble();
double y = input.nextDouble();
double rate = (y/100);
int years = input.nextInt();
}
There's no good reason to use a loop in this case, but I guess it's for learning purposes.
You can make a loop that calculates the new balance a year at a time like this:
for(int i = years; i > 0; i--)
balance = balance * y;
Alternatively use Math.pow(this follows the formula startvalue * rate of change^time = result):
balance = balance * Math.pow(y, years);
I am very new. apologies in advance for my coding. I need to print a table that shows year and then a tab over, and then the value with a next line. The value has to be in decimal form.
I have been reading and searching and mixing my code around. I have found it for 1 variable but not for two in same line. I have tried the printf, I have tried the good ol 100 / 100.0 and I either get errors or the decimal never goes to 2 places. I do not need it rounded, just with 2 spaces after. I am obviously going wrong somewhere. I would appreciate any assistance.
import java.util.Scanner;
public class Investment1 {
public static double futureInvestmentValue(double investmentAmount, double monthlyInterestRate, int years){
double principal = 0.0;
double futureInvestmentValue = 0;
for (years = 1; years <=30; years++){
//calculate futureInvestmentValue
futureInvestmentValue = (investmentAmount * (Math.pow (1 + monthlyInterestRate, years * 12)));
System.out.print(years + "\t" + futureInvestmentValue + "\n");
}//end for
return futureInvestmentValue;
}//end futureInvestmentValue
public static void main(String[] args){
Scanner input = new Scanner (System.in);
//obtain Investment amount
System.out.print("Enter Investment amount: ");
double investmentAmount = input.nextDouble();
//obtain monthly interest rate in percentage
System.out.print("Enter annual interest rate in percentage: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = (annualInterestRate / 1200);
int years = 30;
System.out.println("Years\t" + "Future Value");
System.out.print(years + "\t");
System.out.print(years + "\t" + ((int)(futureInvestmentValue(investmentAmount, monthlyInterestRate, years))) + "\n");
}//end main
}//end Investment
You can use system.out.format():
System.out.format("%d \t %.2f", years, futureInvestmentValue);
you should read about format strings, heres a simple usage example:
System.out.println(String.format("%d %.2f",myint,myfloat));
myint will be printed as an integer (even if it's a floating point value) due to the use of the %d in the format string.
myfloat will be printed as a decimal number with 2 digits after the decimal point, thanks to the %f.2 part in the format string.