Can't use decimals in scanner input [duplicate] - java

This question already has answers here:
Scanner double value - InputMismatchException
(2 answers)
Closed 5 years ago.
I have this code here:
import java.util.Scanner;
public class Loan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter annual interest rate, e.g., 7.35%: ");
double annualInterestRate = input.nextDouble();
double monthlyInterestRate = annualInterestRate / 1200;
System.out.print("Enter number of years as an integer, e.g., 5: ");
int numberOfYears = input.nextInt();
System.out.println("Enter loan amount, e.g., 120000.95:" );
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow
(1 + monthlyInterestRate, numberOfYears * 12));
double totalPayment = monthlyPayment * numberOfYears * 12;
System.out.println("The monthly payment is $" +
(int)(monthlyPayment * 100) / 100.0);
System.out.println("The total payment is $" +
(int)(totalPayment * 100) /100.0);
}
}
The annualInterestRate is a double value but when i try to enter a decimal like 5.4, i get an error. Using whole numbers works perfectly fine.
Anything wrong with the code? Thanks:)

Your locale (Norway) use , as decimal delimiter as it is specified in the list of Oracle looks like :
4.294.967.295,000
As the doc sais :
A scanner's initial locale is the value returned by the Locale.getDefault()
But you can change the Scanner locale with useLocale(Locale) like this :
Scanner sc = new Scanner(ystem.in);
sc.useLocale(Locale.ENGLISH);
As said by the doc
It may be changed via the useLocale(java.util.Locale) method
This will accept a . as delimiter.
The full documentation is here

Related

Can anyone help me remove the comma from my output? [duplicate]

This question already has answers here:
how to print a Double without commas
(10 answers)
Closed 7 years ago.
So my code is correctly outputting the compounded interest periodically, but it is putting my output with a comma. Ex: $1,000.00 I would like the answer to be: $1000.00.
Here is my code guys:
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%,.2f \n", rate, fv);
}
}
I had changed the code for you but as #ajb said in comment, you are getting "," because you have used it while formatting string. For deep understanding read here
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
}
}
Remove the comma from the format string for variable fv:
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
Also here is a discussion about using different (not only comma) symbols for grouping separator.

Create a program that prompt user fa a floating point(double) Fahrenheit and then return equal value in Celsius

import java.util.*;
class TempConver {
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
temperature = in.nextInt();
temperature = (temperature - 32) * 5 / 9;
System.out.printf("Censius Temperatre is = " + temperature);
}
}
I've to write program using information given below.
output formatting - "printf()" instead of print() or println()
Do While loops - repeat a question until a user gives you a valid response
Scanner.HasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Please help me how to write output in 2 place decimal using do while loop. !!
You have all the answers you need in the hints.
Do While loops - repeat a question until a user gives you a valid response And Scanner.hasNextDouble() - method to ascertain whether or not the next item the scanner is about to read works as a double data type
Here you are telling the user, while the input is not a double, then execute the code. Which will be asking the user for input until you get a double
while (!in.hasNextDouble()) {
// code here
}
To round to two decimals you can use Math.round() to round a value to the nearest integer, and multiply temperature by 100 then divide by 100.
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
Full code:
public static void main(String[] args) {
double temperature;
Scanner in = new Scanner(System.in);
System.out.printf("Enter Fahrenheit Temperature: ");
// As long as it is not a double ask for another input
while (!in.hasNextDouble()) {
System.out.printf("Please enter a valid number:");
in.next();
}
temperature = in.nextDouble();
temperature = (temperature - 32) * 5 / 9;
// Use only 2 decimals
int round = (int) Math.round(temperature*100);
temperature = round / 100.0;
System.out.printf("Censius Temperatre is = " + temperature);
}

Java Loan Amortization

Please what could be wrong with my code. it is an iteration approach to: The monthly payment for a given loan pays the principal and the interest. The monthly interest is computed by multiplying the monthly interest rate and the balance (the remaining principal).
The principal paid for the month is therefore the monthly payment minus the
monthly interest. Write a program that lets the user enter the loan amount, number of years, and interest rate and displays the amortization schedule for the loan.
However, i keep getting NaN just to calculate monthly payment.code is as follow:
import java.util.Scanner;
public class Amortization {
public static void main(String[] args) {
//create Scanner
Scanner s = new Scanner(System.in);
//prompt Users for input
System.out.print("Enter loan Amount:");
int loanAmount = s.nextInt();
System.out.print("Enter numberof Years:");
int numberYear =s.nextInt();
System.out.print("Enter Annual Interest Rate:");
int annualRate = s.nextInt();
double monthlyrate= annualRate/1200;
double monthlyPayment = loanAmount*monthlyrate/(1 -1/Math.pow(1+monthlyrate,numberYear*12));
System.out.printf("%6.3f",monthlyPayment);
// TODO code application logic here
}
}
I just wrote code for a similar problem. I share with you my solution.
I got a lot of ideas from http://java.worldbestlearningcenter.com/2013/04/amortization-program.html
public class LoanAmortizationSchedule {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Prompt the user for loan amount, number of years and annual interest rate
System.out.print("Loan Amount: ");
double loanAmount = sc.nextDouble();
System.out.print("Number of Years: ");
int numYears = sc.nextInt();
System.out.print("Annual Interest Rate (in %): ");
double annualInterestRate = sc.nextDouble();
System.out.println(); // Insert a new line
// Print the amortization schedule
printAmortizationSchedule(loanAmount, annualInterestRate, numYears);
}
/**
* Prints amortization schedule for all months.
* #param principal - the total amount of the loan
* #param annualInterestRate in percent
* #param numYears
*/
public static void printAmortizationSchedule(double principal, double annualInterestRate,
int numYears) {
double interestPaid, principalPaid, newBalance;
double monthlyInterestRate, monthlyPayment;
int month;
int numMonths = numYears * 12;
// Output monthly payment and total payment
monthlyInterestRate = annualInterestRate / 12;
monthlyPayment = monthlyPayment(principal, monthlyInterestRate, numYears);
System.out.format("Monthly Payment: %8.2f%n", monthlyPayment);
System.out.format("Total Payment: %8.2f%n", monthlyPayment * numYears * 12);
// Print the table header
printTableHeader();
for (month = 1; month <= numMonths; month++) {
// Compute amount paid and new balance for each payment period
interestPaid = principal * (monthlyInterestRate / 100);
principalPaid = monthlyPayment - interestPaid;
newBalance = principal - principalPaid;
// Output the data item
printScheduleItem(month, interestPaid, principalPaid, newBalance);
// Update the balance
principal = newBalance;
}
}
/**
* #param loanAmount
* #param monthlyInterestRate in percent
* #param numberOfYears
* #return the amount of the monthly payment of the loan
*/
static double monthlyPayment(double loanAmount, double monthlyInterestRate, int numberOfYears) {
monthlyInterestRate /= 100; // e.g. 5% => 0.05
return loanAmount * monthlyInterestRate /
( 1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12) );
}
/**
* Prints a table data of the amortization schedule as a table row.
*/
private static void printScheduleItem(int month, double interestPaid,
double principalPaid, double newBalance) {
System.out.format("%8d%10.2f%10.2f%12.2f\n",
month, interestPaid, principalPaid, newBalance);
}
/**
* Prints the table header for the amortization schedule.
*/
private static void printTableHeader() {
System.out.println("\nAmortization schedule");
for(int i = 0; i < 40; i++) { // Draw a line
System.out.print("-");
}
System.out.format("\n%8s%10s%10s%12s\n",
"Payment#", "Interest", "Principal", "Balance");
System.out.format("%8s%10s%10s%12s\n\n",
"", "paid", "paid", "");
}
}
That's because you are entered number followed by an enter . So your nextLine method call just reads return key while nextInt just reads integer value ignoring the return key. To avoid this issue:
Just after reading input, you call something like:
int loanAmount=s.nextInt();
s.nextLine();//to read the return key.
Also, it might be a good idea to format your code (identation)

Separate two loops in java

I should write a program that reads balance and interest rate, and displays the value of the account in ten years with anually, monthly and daily compounds.
I have written for yearly compounding and for monthly. In the second loop for monthly rate, program reads value of "balance" after compounding yearly, while I need it read primary value. How is it possible to separate two loops, so they do not influence each other? Here is my code:
import java.util.Scanner;
public class BankInterest {
public static void main(String []args) {
System.out.println("Please enter your balance: ");
Scanner keyboard = new Scanner(System.in);
double balance = keyboard.nextDouble();
int years = 0;
int months = 0;
int days = 0;
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRate = keyboard.nextDouble();
while (years<10) {
double interest = balance * interestRate;
balance = balance + interest;
years++;
}
System.out.println("Balance after 10 years with annual interest is " + balance);
while (months<120) {
double interest = balance * interestRate/12;
balance = balance + interest;
months++;
}
System.out.println("Balance after 10 years with monthly interest rate is " + balance);
}
}
When program is run and I input 100 for balance and 0.02 to interest rate, yearly compounding works well and displays:
Balance after 10 years with annual interest is 121.89944199947573
And second loop takes this value as balance and displays:
Balance after 10 years with monthly interest rate is 148.86352955791543
While, if my code was right it should display this number: 122.119943386
You can place both loops in different functions and pass both balance and interesRate as arguments, like below.
import java.util.Scanner;
public class BankInterest {
static public double annualInterest(double balance, double interestRate) {
int years = 0;
while (years < 10) {
double interest = balance * interestRate;
balance = balance + interest;
years++;
}
return balance;
}
static public double monthlyInterest(double balance, double interestRate) {
int months = 0;
while (months < 120) {
double interest = balance * interestRate/12;
balance = balance + interest;
months++;
}
return balance;
}
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your balance: ");
double balance = keyboard.nextDouble();
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRate = keyboard.nextDouble();
System.out.println("Balance after 10 years with annual interest is " +
annualInterest(balance, interestRate));
System.out.println("Balance after 10 years with monthly interest rate is " +
monthlyInterest(balance, interestRate));
}
}
You need to declare two different variables for initial balance and updated balance so that you can access the original balance in both loops. I have shown this below.
public static void main(String []args) {
System.out.println("Please enter your balance: ");
Scanner keyboard = new Scanner(System.in);
double startingBalance = keyboard.nextDouble();
double finalBalance=0;
int years = 0;
int months = 0;
int days = 0;
System.out.println("Please enter the ann1ual interest rate in decimal form: ");
double interestRateYearly = keyboard.nextDouble();
double interstRateMonthly = interestRateYearly;
double interstRateDayliy = interestRateYearly;
while (years<10) {
double interest = startingBalance * interestRateYearly ;
finalBalance = startingBalance + interest;
years++;
}
System.out.println("Balance after 10 years with annual interest is " + finalBalance);
while (months<120) {
double interest = startingBalance * interstRateMonthly /12;
finalBalance = startingBalance + interest;
months++;
}
System.out.println("Balance after 10 years with monthly interest rate is " + finalBalance);
}
}

monthly payment calculator

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 );
}
}

Categories

Resources