I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}
Related
I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for
"Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.
-- A
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// SPLASH
// CONSTANT
// OBJECT
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// VARIABLES
double investment;
double investTotal;
double rate;
double intrest;
int year;
// INPUT
do
{
System.out.print("Enter yearly investment (min $100.00 deposit): ");
investment = input.nextDouble();
}
while (investment < 100);
do
{
System.out.print("Enter intrest rate (%): ");
rate = input.nextDouble()/100;
}
while (rate <= 0);
do
{
System.out.print("Enter number of years: ");
year = input.nextInt();
}
while (year <= 0 || year > 15);
// PROCESSING
investTotal = investment;
for (int perYear = 1; perYear <= year; perYear++)
{
intrest = investTotal*rate;
investTotal = (investment+intrest);
System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
investTotal = investTotal + investment;
}
// OUTPUT
}
}
getCurrencyInstance returns a String and therefor can't be formatted using %.2f.
You better look how NumberFormat works:
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g:
System.out.format("%2s | %.2f\n", 1.001, 1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually, monthly, daily;
double balance;
int year = 10 ;
System.out.println("Enter the amount you will like to deposit or type exit to end.");
int deposit = key.nextInt();
annually = deposit * Math.pow((1 + rate/1),year);
monthly = deposit * Math.pow((1 + rate/12),year);
daily = deposit * Math.pow((1 + rate/365),year);
while (deposit)
{
}
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
This is what I currently have. What I am trying to accomplish is to make a loop to add the first outcome with the next one. Also make one formula instead of having three to find the annually, monthly and daily.
First and foremost, asking someone to write out your homework is really unethical, and not helpful for you in the long run. If you don't care about the long run, consider taking a different class. In a career scenario, you're expected to write code on your own.
Secondly, to actually answer your question, here are some tips:
It seems like you want to gather a value (deposit) from the user, and then calculate the Compound Interest for said value. Your program also needs to not exit until the user says to exit. i.e. they want to calculate the CI for a set of numbers.
First step is to check the value from the user. If it is a number, then do calculations on it. If it is a String, then check if it is "exit". In Java, this amounts to writing out an if-statement, and making use of the very helpful "instanceof" keyword. If you haven't learned about that, give this a read, or ask your teacher.
For the calculations part, you simply do calculations on the user's input while the input is not a string set to "exit".
Finally, print out your calculations.
That's it. Your code already has the calculation formulas down, so you just need to code the logic for handling user input.
import java.util.Scanner;
import java.lang.Math;
public class HelloWorld {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How much money you want to deposit?");
int principle = sc.nextInt();
System.out.println("what is the rate you want?");
float rate = sc.nextFloat();
System.out.println("After how many years, you want to see your money?");
int year = sc.nextInt();
System.out.println("How many compounds in a year?");
int partialTime = sc.nextInt();
double b = year * partialTime;
double a = 1 + (rate/(partialTime*100));
double x = principle * (Math.pow(a,b));
System.out.println("Your interest in given time would be " + x);
}
}
A couple of suggestions - since you want to check user input against both String and int types, you could define a String type variable to hold the user input, and then do a try/catch to parse it as an Integer, if it's not an Integer check if the input equals "exit" (using the String.equals() method).
import java.util.*;
public class Project3{
public static void main(String[] args)
{
Scanner key = new Scanner (System.in);
double rate = 0.05;
double annually = 0, monthly = 0, daily = 0;
double balance;
int year = 10, deposit = 0 ;
String userinput = "";
do {
try {
System.out.println("Enter the amount you will like to deposit or type exit to end.");
userinput = key.nextLine();
deposit = Integer.parseInt(userinput);
}
catch (Exception e){
if (!userinput.equals("exit")){
System.out.println("Didn't recognize that input, please try again...");
}
else{
break;
}
}
} while (!userinput.equals("exit"));
annually += deposit * Math.pow((1 + rate/1),year);
monthly += deposit * Math.pow((1 + rate/12),year);
daily += deposit * Math.pow((1 + rate/365),year);
System.out.println(annually);
System.out.println(monthly);
System.out.println(daily);
}
}
Depending on how you want the output, you can easily adjust the scope of the loop to display the amounts after each valid deposit input, or just once at the end, after the user enters "exit".
Hope this helps.
I am trying to program an amortization calculator in which the user can enter a value for balance, a value for their interest rate in decimal form, and a value for monthly payment. With this information I want to output an interest amount in dollars, a principal amount, and a new balance. Here is my code:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner pmt, interest, balance = new Scanner(System.in);
System.out.println("What is your balance?");
double b = balance.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = interest.nextDouble();
System.out.println("What is your monthly payment?");
double p = pmt.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
You should not declare 3 scanners to read from the standard input. Declare one and just keep reading from it. Like this:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println("What is your balance?");
double b = input.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = input.nextDouble();
System.out.println("What is your monthly payment?");
double p = input.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
The main point here is that a scanner is the object that reads from an input stream, not the value being read. You don't need a new scanner for every value you want to read.
As #nhouser9 says, you don't need three scanners and answering your question the compiler says that the variables are not initialized because you are only initializing the last of them (balance). Multiple initializing in java won't functions as you expected (initialize all the variables with the same value).
The code is below. The program runs a series of calculations based on data input by the user. My problem is that for the most important thing I'm looking for, total kg CO2 emissions, I continually get an answer of 0.0. What I need is a sum of the individual total emissions as calculated in each method, i.e. the values which are printed with the following: System.out.println(trans); System.out.println(elec); and System.out.println(food);
The total should be something like 25040 or whatever, depending on the value of the inputs provided by the user, but I'm constantly getting a total of 0.0., which is obviously false. Could have something to do with the way I've initialized my variables, or something to do with the limitations of returning values from methods. I just don't know what to do. How should I tackle this? All help greatly appreciated!
import java.util.Scanner;
public class CarbonCalc {
public static void main(String[] args) {
double trans = 0;
double elec = 0;
double food = 0;
giveIntro();
determineTransportationEmission(null);
determineElecticityEmission(null);
determineFoodEmission(null);
calculateTotalEmission(trans, elec, food);
//printReport(trans, elec, food);
}
//Gives a brief introduction to the user.
public static void giveIntro() {
System.out.println("This program will estimate your carbon footprint");
System.out.println("(in metric tons per year) by asking you");
System.out.println("to input relevant household data.");
System.out.println("");
}
//Determines the user's transportation-related carbon emissions.
public static double determineTransportationEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will first begin with your transportation-related carbon expenditures...");
System.out.print("How many kilometres do you drive per day? ");
double kmPerDay = console.nextDouble();
System.out.print("What is your car's fuel efficiency (in km/litre)? ");
double fuelEfficiency = console.nextDouble();
System.out.println("We now know that the numeber of litres you use per year is...");
double litresUsedPerYear = 365.00 * (kmPerDay / fuelEfficiency);
System.out.println(litresUsedPerYear);
System.out.println("...and the kg of transportation-related CO2 you emit must be...");
//Final calculation of transportation-related kgCO2 emissions.
double trans = 2.3 * litresUsedPerYear;
System.out.println(trans);
System.out.println("");
return trans;
}
//Determines the user's electricity-related carbon emissions.
public static double determineElecticityEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your electricity-related carbon expenditures...");
System.out.print("What is your monthly kilowatt usage (kWh/mo)? ");
double kWhPerMonth = console.nextDouble();
System.out.print("How many people live in your home? ");
double numPeopleInHome = console.nextDouble();
System.out.println("The kg of electricity-related CO2 you emit must be...");
//Final calculation of electricity-related kgCO2 emissions.
double elec = (kWhPerMonth * 12 * 0.257) / numPeopleInHome;
System.out.println(elec);
System.out.println("");
return elec;
}
//Determines the user's food-related carbon emissions.
public static double determineFoodEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your food-related carbon expenditures...");
System.out.print("In a given year, what percentage of your diet is meat? ");
double meat = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is dairy? ");
double dairy = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is fruits and veggies? ");
double fruitVeg = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is carbohydrates? ");
double carbs = console.nextDouble();
//Final calculation of food-related kgCO2 emissions.
System.out.println("The kg of food-related CO2 you emit must be...");
double food = (meat * 53.1 + dairy * 13.8 + fruitVeg * 7.6 + carbs * 3.1);
System.out.println(food);
System.out.println("");
return food;
}
//Calculates total emissions across all sources.
public static double calculateTotalEmission(double trans, double elec, double food) {
System.out.println("Your total kg of CO2 emitted across all sources is equal to...");
double total = trans + elec + food;
System.out.println((double) total);
System.out.println("");
return total;
}
}
Ah!! Thank you very much Lyju. I did the following and it all worked well.
From this:
double trans = 0;
double elec = 0;
double food = 0;
To this:
double trans = determineTransportationEmission(null);
double elec = determineElecticityEmission(null);
double food = determineFoodEmission(null);
The second problem which popped up here had to do with not correctly passing the Scanner parameter to the multiple methods.
I fixed that by adding the following to the main method:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double trans = determineTransportationEmission(console);
double elec = determineElecticityEmission(console);
double food = determineFoodEmission(console);
giveIntro();
calculateTotalEmission(trans, elec, food);
}
And because I had three scanner objects, one for each method, I simply removed the Scanners in each and can now pass a single Scanner from my main method to each of the others.
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 :-)