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 :)
Related
I am writing a program that takes the loan amount, interest rate, and total paid from a text file. It is supposed to update the interest rate to total interest and the same for total paid. Then it is supposed to calculate the monthly payments.
I keep getting the error operators can't be applied to java string for the calculations including loan. I'm guessing this is because you can't use strings in calculations? Maybe i'm wrong. I am stumped.
Example input:
56750.00 .065 72.00
43675.00 .075 48.00
64950.00 .045 36.00
24799.00 .085 48.00
My code
import java.io.*;
import java.util.*;
import java.text.*;
public class DB4
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
String loan;
int Count = 0;
double interest = 0;
double Numberofmonths = 0;
double totint;
double totpay;
double monthly;
Scanner inFile= new Scanner(new FileReader("Project4InData.txt"));
PrintWriter outFile = new PrintWriter("Project4.out");
while (inFile.hasNext())
{
loan = inFile.next();
interest = inFile.nextDouble();
Numberofmonths = inFile.nextDouble();
// calcs
totint = interest * loan;
totpay = totint + loan;
monthly = loan / 12;
outFile.print("Loan Amount: " + loan);
outFile.print(" ");
outFile.println("Interest: " + totint);
outFile.print(" ");
outFile.println("Total paid: " + totpay);
outFile.print(" ");
outFile.println("Monthly payment: " + monthly);
}
inFile.close();
outFile.close();
}
}
loan is a string, so interest * loan doesn't make sense.
To realize why it doesn't make sense to apply * to a string, consider what "abc" * 2 or "def" * "ghi" would mean. (Absolutely nothing, which is why Java doesn't allow you to perform those operations on string objects).
You can apply + to strings, but it doesn't do addition, it does concatenation.
Same logic applies to the / operator.
Make loan a double.
package travelCost;
import java.util.Scanner;
public class travelCost {
public static void main(String[] args) {
//Scanner function
Scanner in = new Scanner(System.in);
//define problem variables
//first
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
//Here i want the user to input a string and then based upon the answer //section into the for loop
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec"))
{
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance/milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ", totalCostElec);
} else if (type.equals("gas: ")
{
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance/mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
}else
{
System.out.println("Please resubmit entry");
}
System.out.println();
}
}
After the corrections which mentioned by Paul, here is the complete code:
travelCost.java
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double distance;
double mpg;
double pricePerGallon;
double milesPerKwh;
double pricePerKwh;
double totalCostGas;
double totalCostElec;
String type;
System.out.println("Enter whether the car is 'elec' or 'gas': ");
type = in.next();
if (type.equals("elec")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the total Miles per Kwh: ");
milesPerKwh = in.nextDouble();
System.out.println("Enter the Total Price per Kwh: ");
pricePerKwh = in.nextDouble();
totalCostElec = (distance / milesPerKwh) * pricePerKwh;
System.out.printf("The trip is going to cost $%5.2f: ",
totalCostElec);
} else if (type.equals("gas")) {
System.out.println("Enter the Total Distance in Miles: ");
distance = in.nextDouble();
System.out.println("Enter the Miles per Gallon: ");
mpg = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
System.out
.println("Enter the total Price per Gallon of Gasoline: ");
pricePerGallon = in.nextDouble();
totalCostGas = (distance / mpg) * pricePerGallon;
System.out.printf("The trip is going to cost $%5.2f", totalCostGas);
} else {
System.out.println("Please resubmit entry");
}
System.out.println();
}
Input:
elec 100 10 2
Output:
The trip is going to cost $20.00:
make it
else if (type.equals("gas"))
There are 4 problems with this:
The line } else if (type.equals("gas: ") needs another ) at the end.
In the "gas" case, you are using the variable distance but you do not give it a value.
While if (type.equals("elec")) is the correct syntax (answering your question), it is usually better to write if ("elec".equals(type)) because this will not throw a NullPointerException if type == null.
It should be "gas", not "gas: ".
As Paul mentions, your if statement syntax is correct, but it is good practice to start with the hard coded strings ("elec" and "gas") in order to avoid NullPointerExceptions. As mentioned in the other answers, the if else should be using "gas" instead of "gas: ". To help avoid those kinds of errors, you might consider making "elec" and "gas" into static final String constants. If you use constants, you'll know that they are the same throughout your program. You might also want to call type.toLowerCase() in the event that the user enters the response in uppercase.
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 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.
The assignment is:
Write a program that provides 20% discount for member who purchase any two books at XYZ bookstore. (Hint: Use constant variable to the 20% discount.)
I have done the coding, but cannot prompt book name, and then show the discounted price. Please see my coding below and modify it as your needs.
import java.util.Scanner;
public class Book_Discount {
public static void main(String args[]) {
public static final double d = 0.8;
Scanner input = new Scanner(System.in);
int purchases;
double discounted_price;
System.out.print("Enter value of purchases: ");
purchases = input.nextInt();
discounted_price = purchases * d; // Here discount calculation takes place
// Displays discounted price
System.out.println("Value of discounted price: " + discounted_price);
}
}
For prompting the book name as well, you write something like:
/* Promt how many books */
System.out.print("How many books? ");
int bookCount = scanner.nextInt();
scanner.nextLine(); // finish the line...
double totalPrice = 0.0d; // create a counter for the total price
/* Ask for each book the name and price */
for (int i = 0; i < bookCount; ++i)
{
System.out.print("Name of the book? ");
String name = scanner.nextLine(); // get the name
System.out.print("Price of the book? ");
double price = scanner.nextDouble(); // get the price
scanner.nextLine(); // finish the line
totalPrice += price; // add the price to the counter
}
/* If you bought more than 1 book, you get discount */
if (bookCount >= 2)
{
totalPrice *= 0.8d;
}
/* Print the resulting price */
System.out.printf("Total price to pay: %.2f%n", totalPrice);