I am getting an error trying to code a program which calculates interest on a loan, and displays information back with certain decimal positions. I need the loanInterest to display at 3.546%, or something like that with 3 decimal places. I was able to get the totalInterest to display properly, but I dont know if this is because it was a new value I just established. When I try to run my program as seen below, I get a "float cannot be dereferenced" error.
public class SarahShelmidineModule2Project {
public static void main(String[] args) {
//Being programing for Module 2 project
// Welcome the user to the program
System.out.println("Welcome to the Interest Calculator");
System.out.println(); // print a blank line
// create a Scanner object named sc
Scanner sc = new Scanner(System.in);
// perform interest calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get info from user on loan amount and interest rates and store data
System.out.print("Enter loan amount: ");
double loanAmount = sc.nextDouble();
System.out.print("Enter interest rate: ");
float loanInterest = sc.nextFloat();
// calculate the interest and convert to BigDecimal and rounding for totalInterest
BigDecimal decimalloanAmount = new BigDecimal (Double.toString(loanAmount));
BigDecimal decimalloanInterest = new BigDecimal (Double.toString(loanInterest));
BigDecimal totalInterest = decimalloanAmount.multiply(decimalloanInterest);
totalInterest = totalInterest.setScale(2, RoundingMode.HALF_UP);
loanInterest = loanInterest.setScale(3, RoundingMode.HALF_UP);
System.out.println(); // print a blank line
// display the loan amount, loan interest rate, and interest
// also format results to percent and currency
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
String message = "Loan amount: " + currency.format(loanAmount) + "\n"
+ "Interest rate: " + percent.format(loanInterest) + "\n"
+ "Intrest: " + currency.format(totalInterest) + "\n";
System.out.println(message);
// inquire if user would like to continue with application
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
Below is the error I get when I run this:
Welcome to the Interest Calculator
Enter loan amount: 10932
Enter interest rate: .0934
Exception in thread "main" java.lang.RuntimeException: Uncompilable
source code - Erroneous sym type: <any> at
sarahshelmidinemodule2project.SarahShelmidineModule2Project.main(SarahShelmidineModule2Project.java:45)
Just change
float loanInterest = sc.nextFloat();
with
BigDecimal loanInterest = new BigDecimal(sc.nextFloat());
and you will resolve "float cannot be derefenced" since float is a primitive type and has not method setScale.
About printing right number of decimals, use something like this:
String currencySymbol = Currency.getInstance(Locale.getDefault()).getSymbol();
System.out.printf("%s%8.5f\n", currencySymbol, totalInterest);
This code will use 5 decimals, but be sure that your BigDecimal scale is at least 5, otherwise you will get not significant zeros.
Related
I am creating my first java program for the class. The purpose of the program is to calculate interest for deposit for year one and year two. My issue comes when the code outputs the final totals. The last two lines are supposed to use System.out.printf(). I keep getting the error Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'i'. How do I correct this?
public static void main(String... args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello World!");
//declares variables
double interest = 0;
double balance = 0;
double deposit = 0;
double secondYearBalance = 0;
double secondYearInterest = 0;
//displays welcome message
System.out.println("Welcome to George's Interest Calculator");
//prompts user for input
System.out.println("Please enter your initial deposit:");
deposit = keyboard.nextInt();
//Finds outs interest interest earned on deposit
interest = deposit * TAXRATE;
//Finds out the amount of the balance
balance = deposit + interest;
//finds out second year balance
secondYearInterest = balance * TAXRATE;
secondYearBalance = secondYearInterest + balance;
//Outputs totals
System.out.printf("Your balance after one year with a 4.9% interest rate is $%7.2f %n", balance);
System.out.printf("Your balance after two years with a 4.9% interest rate is $%7.2f %n", secondYearBalance);
System.out.println();
}
The % symbol is used in a printf string for 'put a variable here'.
That's problematic when you write 4.9% interest rate because java thinks that % i is you saying: "a variable goes here". The fix is trivial; a double % is how you write a single percent. Thus:
System.out.printf("Your balance after one year with a 4.9%% interest rate is $%7.2f %n", balance);
import java.util.Scanner;
public class Taxes {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.printf("Enter the employees first name: ");
Scanner input = new Scanner(System.in);
String fName = input.nextLine();
System.out.printf("Enter the employees last name: ");
String lName = input.nextLine();
System.out.printf("Enter the hours worked for the week: ");
double hours = input.nextDouble();
System.out.printf("Enter the hourly pay rate: ");
double pay = input.nextDouble();
double gross = hours * pay;
System.out.printf("Enter the federal tax withholding: ");
double fed = input.nextDouble();
double fTax = gross * fed;
System.out.printf("Enter the state tax withholding: ");
double state = input.nextDouble();
double sTax = gross * state;
double Ttax = sTax + fTax;
double net = gross - Ttax;
System.out.printf(
"Employee Name:%s %s\n\nHours Worked:%s hours\n\nPay Rate:$%.2f\n\nGross pay:$%.2f\n\nDeductions: \n\n\tFederal Withholding:(%.2f%%)$%.2f \n\n"
+ "\tState Withholding:(%.2f%%)$%.2f\n\n\tTotal Witholding:$%.2f\n\nNet Pay:$%.2f",
fName, lName, hours, pay, gross, fed, fTax, state, sTax, Ttax, net);
input.close();
}
}
I need to declare two more variables to get the Federal and State tax withholdings to show as a percent.
Example They show as (00.20%) I need them to return as a whole percent like (20.00%)
I've tried declaring new variable at the bottom such as:
statewit = sTax * 100;
fedwit = fTax * 100;
to get the percents to return as I want but it tends to add that total to the net at the end.
Any help would be appreciated greatly, thanks!
Try this.
double percent=12.34;
System.out.printf("%.2f%%", percent);
// or in different convention "percent as number *100"
System.out.printf("%.2f%%", percent*100.0);
EDIT: Your Question can be divided in two:
Convention in which numbers are used (normal or percent scaled *100)
Real formatting to String
BTW Your code is long and has very little to FORMATTING.
Java has no special type for percent values. Types: double, BigDecimal can be used with his behaviour, or integer types too, if programmer keep integer convention
EDIT: thanks Costis Aivalis , comma corrected :)
I want to figure out how I can format the output as money. As I am a beginner at Java, I would like the most simple solution possible although I am open to all suggestions.
public static void main(String[] args)
{
int numUnits;
double price;
String item;
Scanner scan = new Scanner(System.in);
// get the data
System.out.println("How many units?");
numUnits = scan.nextInt();
System.out.println("What is the price?");
price = scan.nextDouble();
scan.nextLine();
System.out.println("What is the name of the item?");
item = scan.nextLine();
//calculations
double totalCost = numUnits * price;
System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + totalCost);
}
}
Well there are a number of ways you might be able to do it, you could use NumberFormat.getCurrencyInstance(), which will allow you to format the value based on the current locale properties...
System.out.println(numUnits + " units of "+ item + " were purchased for $"+
price + " each for a total cost of $" + NumberFormat.getCurrencyInstance().format(totalCost));
You could also format the NumberFormat to suit you needs by getting a reference to the instance first...
NumberFormat nf = NumberFormat.getCurrencyInstance();
// Customise format properties...
double amount =500.0;
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(new Locale("en", "US"));
System.out.println(currencyFormatter.format(amount));
You should use proper locale for which ever currency you awnt to use
I am new to java and I can't figure out what is wrong with my code. After the user inputs annual income and # of exemptions, the code stops working. There are no error messages on my console either. Please help me.
The program:
My code:
import java.util.Scanner;
public class TaxRate {
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
// before asking the user for input
final double TAX_RATE = 0.12;
System.out.println ("Type in your name:");
String name;
name = sc.next();
System.out.println (name + ", type in your annual income and number of exemptions, separated by spaces:");
double income, exempt;
income = sc.nextDouble();
exempt = sc.nextDouble();
sc.close();
} // main method
} // lab class
Where you have
double num2 = 2000 * exempt;
num2 = sc.nextDouble();
you are calculating num2 and then waiting for the user to enter it.
Where you have
double adjustedGrossIncome = income - num2;
adjustedGrossIncome = sc.nextDouble();
you are calculating adjustedGrossIncome and then waiting for the user to enter it.
Where you have
double tax = TAX_RATE * adjustedGrossIncome;
tax = sc.nextDouble();
you are calculating tax and then waiting for the user to enter it.
If you take out the nextDouble() lines in those three cases, your program will run along instead of stopping for user input.
Your problem is that you ask for an input for tax that you already calculated, since that would be a useless line of code.
I wrote a simple program that receives several inputs and it does a future investment calculation.
However, for some reason, when I enter the following values:
investment = 1
interest = 5
year = 1
I get Your future value is 65.34496113081846 when it should be 1.05.
import java.util.*;
public class futurevalue
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("This program will calculate your future investment value");
System.out.println("Enter investment amount: ");
double investment = sc.nextDouble();
System.out.println("Enter annual interest amount: ");
double interest = sc.nextDouble();
System.out.println("Enter number of years: ");
int year = sc.nextInt();
double futureValue = investment * (Math.pow(1 + interest, year*12));
System.out.println("Your future value is " + futureValue);
}
}
Found my mistake. I divided my interest twice.
You should divide your interest by 100.
How is the interest rate being entered? Should you not divide it by 100 before adding 1 inside Math.pow?
Example: Monthly interest = 1%, if you enter 1, your Math.pow would be Math.pow(1+1, year*12) which would be incorrect.
Yes, your main error is not dividing by 100 to convert from percents to proportion, but you have another error:
If you have an APR of 5% the formula you need to use to calculate a compounding monthly interest isn't 5%/12, it's
(0.05+1)^(1/12)-1
And then the return for that investment ends up being:
1 * ( (0.05+1)^(1/12)-1 +1 )^(1 * 12) =
1 * ( (0.05+1)^(1/12) )^(12) =
1 * ( 0.05+1 ) = 1.05
exactly.