Operators can't be applied to java string - java

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.

Related

How to work out the total cost of an item using a Scanner?

I need to write a program that will allow the user to type in the name of an item followed
by a space and then the cost of the item. The user must continually type in item
names and costs. The program will terminate when the user enters "STOP" as input.
The program must determine the total cost of all the items entered.
Sample Input:
coke 12.50
pie 11.65
fanta 12.00
coffee 13.78
STOP
Sample Output:
Total Cost: R49.93
import java.util.Scanner;
import javax.swing.JOptionPane;
String details = "";
double total_cost = 0;
while(!details.equals("STOP")){
details = JOptionPane.showInputDialog("Enter item cost and name");
Scanner sc = new Scanner(details);
while(sc.hasNextDouble()){
double price = sc.nextDouble();
total_cost = total_cost + price;
System.out.println("Total Cost: R" + total_cost);
However my code outputs nothing except a build successful`enter code here. What am I doing wrong? Excuse the lack of polish in my question I am new to Stack Overflow.
You have to match STOP with the next token from the input, not with the whole of input. Also, as per your requirement, the input should be outside the loop. Do it as follows:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
String details = JOptionPane.showInputDialog("Enter item cost and name");
Scanner sc = new Scanner(details);
double total_cost = 0;
while (sc.hasNext() && !sc.next().equalsIgnoreCase("STOP")) {
if (sc.hasNextDouble()) {
double price = sc.nextDouble();
total_cost = total_cost + price;
}
}
System.out.println("Total Cost: R" + total_cost);
}
}
Output:
Total Cost: R49.93
[Update]
If you want to process individual entries e.g. coke 12.50 and then pie 11.65 and so on, you can do it as follows:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
double total_cost = 0;
String details;
do {
details = JOptionPane.showInputDialog("Enter item cost and name");
String[] tokens = details.split("\\s+");
if (tokens.length >= 2) {
try {
double price = Double.parseDouble(tokens[1]);
total_cost = total_cost + price;
} catch (IllegalArgumentException e) {
System.out.println("Wrong input");
}
}
} while (!details.equalsIgnoreCase("STOP"));
System.out.println("Total Cost: R" + total_cost);
}
}

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.06"

I have been trying to make a simple program in eclipse for a school project, but I keep getting this after I enter my interest rate. I am relatively new to coding and programming in general, and java is new to me as of this month so any help is appreciated. The code is this:
import java.util.Calendar;
import java.util.Locale;
import java.util.Scanner;
public class Interest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
//Input ============================
System.out.println("Initial loan total:"); //cost
String cost;
cost = in.nextLine();
System.out.println("Down payment:"); //down
String down;
down = in.nextLine();
System.out.println("Length of term:"); //term
String term;
term = in.nextLine();
System.out.println("Interest rate (decimal form):"); //rate
String rate;
rate = in.nextLine();
int principle1 = Integer.parseInt(cost) - Integer.parseInt(down);
String hundred;
hundred = "100";
int interest = Integer.parseInt(rate) * Integer.parseInt(hundred);
//Output ===========================
Calendar c = Calendar.getInstance();
System.out.format("%tB %td, %tY", c,c,c);
System.out.println("");
System.out.println("The initial cost of the loan is $" + cost);
System.out.println("The down payment is $" + down);
System.out.println("The principle is $" + principle1);
System.out.println("The term is " + term + " months");
System.out.println("The interest rate is " + interest + "%");
System.out.println("The monthly patments are $");
in.close();
}
}
When I run the program it lets me put in the initial loan, down payment and length of term but as soon as I put in 0.06 for the interest rate it gives me the error message. I would also like to point out that I have a limited understanding of how the math in my code works.
the problem is that you are trying to parse 0.06 to Integer and 0.06 is float.
use Float.parseFloat(rate); and your interest should be a float too float interest

Multiply all values together in string format printing in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've only had a few hours practicing and learning Java so I'm still learning the basics.
I'm reading values from a text file, which contains:
Single
60
112.50
Master
70
2227.50
Penthouse
5
5000.00
(So it appears as when run)
Room Type: Single, Bookings: 60, Room Price: £112.00, Income: £6,750.00, Tax: 1350.00
And so fourth with each room.
I've printed all the values in a string format which is required. However, my problem is really simple.
I just want to add all the income together in a totalincome variable and add all the paidTax together in a totalpaidTax variable, then continue to print out it, to basically show the total tax paid and total income from all the rooms.
Although, I just don't know how to write it. I've had multiple attempts at trying but just no luck.
Here's my current code.
import java.io.FileReader;
import java.util.Scanner;
public class WagesCalculator {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
Scanner file = new Scanner(new FileReader("task3.txt"));
Scanner sc = new Scanner(System.in);
//Current tax variable value
double tax = 20;
//User Input Y or N to change tax variable value
System.out.println("- - Hotel Tax System - -");
System.out.print("Do you want to specify a custom Tax Rate? [Y|N]: ");
//if statement to change tax variable value subject to Y or N
if (sc.next().equalsIgnoreCase("Y")) {
System.out.print("Please enter the new tax value: ");
tax = new Scanner(System.in).nextInt();
}
//Prints out current tax value
System.out.println("The current tax rate is " + tax+".");
while (file.hasNext()) {
String name = file.next();
int numberOfBookings = file.nextInt();
double price = file.nextDouble();
double income = numberOfBookings * price;
double paidTax = income*(tax/100);
//String format print out final calculations
System.out.printf("Room Type: %s, Bookings: %d, Room Price: £%.2f, Income: £%.2f, Tax: %.2f %n", name, numberOfBookings, price, income, paidTax);
}
file.close();
}
}
Objects are your friend.
Create an object for each Room in your input.
Store the Rooms in a List.
Aggregate values from the List.
Print accordingly.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class WagesCalculator
{
public static void main(String[] args)
throws Exception
{
WagesCalculator wc = new WagesCalculator();
wc.calculate();
}
public void calculate()
throws FileNotFoundException
{
Scanner file = new Scanner(new FileReader("task3.txt"));
Scanner sc = new Scanner(System.in);
// Current tax variable value
double tax = 20;
// User Input Y or N to change tax variable value
System.out.println("- - Hotel Tax System - -");
System.out.print("Do you want to specify a custom Tax Rate? [Y|N]: ");
// if statement to change tax variable value subject to Y or N
if (sc.next().equalsIgnoreCase("Y"))
{
System.out.print("Please enter the new tax value: ");
tax = new Scanner(System.in).nextInt();
}
// Prints out current tax value
System.out.println("The current tax rate is " + tax + ".");
List<Room> rooms = new ArrayList<Room>();
while (file.hasNext())
{
String name = file.next();
int numberOfBookings = file.nextInt();
double price = file.nextDouble();
rooms.add(new Room(tax, name, numberOfBookings, price));
}
file.close();
rooms.stream().forEach(e -> System.out.println(e));
double totalIncome = rooms.stream().map(r -> r.income)
.reduce((a, b) -> a + b).orElse(0.0);
double totalTax = rooms.stream().map(r -> r.tax).reduce((a, b) -> a + b)
.orElse(0.0);
System.out.printf("Total income was: %d\nTotal tax was %d\n", totalIncome,
totalTax);
}
class Room
{
double tax;
String name;
int numberOfBookings;
double price;
double income;
double paidTax;
public Room(double tax, String name, int numberOfBookings, double price)
{
this.tax = tax;
this.name = name;
this.numberOfBookings = numberOfBookings;
this.price = price;
this.income = numberOfBookings * price;
this.paidTax = income * (tax / 100);
}
#Override
public String toString()
{
return String.format(
"Room Type: %s, Bookings: %d, Room Price: £%.2f, Income: £%.2f, Tax: %.2f %n",
name, numberOfBookings, price, income, paidTax);
}
}
}

Formatting percentages with printf

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 :)

Compare loans with various interest rates java

I am new to Java and just now started with loops.
I have tried to do this exercise:
Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.
So far this what i have got:
import java.util.Scanner;
public class compareLoansWithInterestRates {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Loan Amount :");
int loan = input.nextInt();
System.out.print("Number of Years" );
int years = input.nextInt();
double monthPay, totalPay,interestRate;
System.out.println( "Interest Rate \t Monthly Payment \t Total Payment");
for(double rate =0.05; rate <=0.08; rate++ ){
for (int month = 1; month <= (years*12);month++){
rate +=1/8;
monthPay = loan* rate/(1-(Math.pow(1+rate,years*12)));
totalPay = monthPay*years*12;
interestRate= rate*100;
System.out.println("\t"+interestRate+" \t "+monthPay+"\t"+totalPay);
Why doesn't it work?
Just looking at your code briefly, you're incrementing rate within your 'outer for' loop using rate++ (which will increment by 1, not 0.01). You then increment rate again within the month loop by 1/8. Try removing 'rate++' from the outer loop. Not positive this will fix all your issues, but this is just a quick observation.
Where to start…
First of all: Java:
for(double rate =0.05; rate <=0.08; rate++ ){
this is good for int, not for double
rate +=1/8;
1/8 is much more then 0.125% you are looking for. It's not Java, but mathematics.
The second line should not be here at all, and for loop should be:
for(double rate =0.05; rate <=0.08; rate+=0.00125 ){
Unfortunately, your algorithm seems to be wrong too, so this change won't fix everything. But from Java point of view it will be rather ok.
I think this'll work
for (double i = 5; i <= 8; i += 0.125) {
double rate = i / 100;
monthPay = loan * (Math.pow(1 + (rate / 12), years * 12)) / 12;
totalPay = monthPay * years * 12;
interestRate = i;
System.out.println("\t" + interestRate + " \t " + monthPay + "\t" + totalPay);
}
I put together a simple loan calculator which is slightly different from yours, to show you just how much work goes into the input and output of a Java application.
Here's the input and output.
Loan Amount 60000
Number of Months 60
Yearly Interest Rate 6
Payments on a $60,000.00 loan for 60 months
Monthly Payment Total Payment
4.000% $1,104.99 $66,299.48
4.250% $1,111.77 $66,706.40
4.500% $1,118.58 $67,114.87
4.750% $1,125.41 $67,524.88
5.000% $1,132.27 $67,936.44
5.250% $1,139.16 $68,349.54
5.500% $1,146.07 $68,764.18
5.750% $1,153.01 $69,180.37
6.000% $1,159.97 $69,598.09
6.250% $1,166.96 $70,017.34
6.500% $1,173.97 $70,438.13
6.750% $1,181.01 $70,860.46
7.000% $1,188.07 $71,284.31
7.250% $1,195.16 $71,709.70
7.500% $1,202.28 $72,136.61
7.750% $1,209.42 $72,565.06
8.000% $1,216.58 $72,995.02
Here's the code that does the actual loan calculation to get the monthly amount.
private double calculateMonthlyPayment(double interestRate) {
double monthlyInterestRate = interestRate / 12D;
double numerator = (double) loanAmount * (monthlyInterestRate);
double denominator = Math.pow(1 + (monthlyInterestRate),
(double) -months);
denominator = 1D - denominator;
return numerator / denominator;
}
Pretty straightforward, right.
Now, I'm going to show you all of the code that gathered the input and produced the output. It's way longer than just the calculation. Go through the code as best you can, and I'll explain it as best I can.
package com.ggl.testing;
import java.text.NumberFormat;
import java.util.Scanner;
public class InterestRateCalculator implements Runnable {
private static final NumberFormat CF = NumberFormat.getCurrencyInstance();
private static final NumberFormat NF = NumberFormat.getNumberInstance();
private double interestRate;
private int loanAmount;
private int months;
#Override
public void run() {
getInputs();
produceOutputs();
}
public void getInputs() {
Scanner input = new Scanner(System.in);
System.out.print("Loan Amount ");
loanAmount = input.nextInt();
System.out.print("Number of Months ");
months = input.nextInt();
System.out.print("Yearly Interest Rate ");
interestRate = input.nextDouble();
input.close();
}
public void produceOutputs() {
double[] interestRates = new double[17];
double interestRate = this.interestRate - 2.0D;
for (int i = 0; i < interestRates.length; i++) {
interestRates[i] = interestRate / 100D;
interestRate += 0.25D;
}
String header = displayHeader();
System.out.println(" ");
System.out.println(header);
System.out.print(leftPad(" ", 10, ' '));
System.out.print(leftPad("Monthly Payment", 15, ' '));
System.out.println(leftPad("Total Payment", 15, ' '));
for (int i = 0; i < interestRates.length; i++) {
String s = displayInterestRate(interestRates[i]) + " ";
System.out.print(leftPad(s, 10, ' '));
double monthlyPayment = calculateMonthlyPayment(interestRates[i]);
System.out.print(leftPad(CF.format(monthlyPayment), 15, ' '));
double totalPayment = monthlyPayment * months;
System.out.print(leftPad(CF.format(totalPayment), 15, ' '));
System.out.println("");
}
}
private double calculateMonthlyPayment(double interestRate) {
double monthlyInterestRate = interestRate / 12D;
double numerator = (double) loanAmount * (monthlyInterestRate);
double denominator = Math.pow(1 + (monthlyInterestRate),
(double) -months);
denominator = 1D - denominator;
return numerator / denominator;
}
private String displayHeader() {
StringBuilder builder = new StringBuilder();
builder.append("Payments on a ");
builder.append(CF.format(loanAmount));
builder.append(" loan for ");
builder.append(NF.format(months));
builder.append(" months");
builder.append(System.getProperty("line.separator"));
return builder.toString();
}
private String displayInterestRate(double interestRate) {
return String.format("%.3f", interestRate * 100D) + "%";
}
private String leftPad(String s, int length, char padChar) {
if (s.length() > length) {
return s.substring(0, length);
} else if (s.length() == length) {
return s;
} else {
int padding = length - s.length();
StringBuilder builder = new StringBuilder(padding);
for (int i = 0; i < padding; i++) {
builder.append(padChar);
}
builder.append(s);
return builder.toString();
}
}
public static void main(String[] args) {
new InterestRateCalculator().run();
}
}
The first thing that I did was use the InterestRateCalculator class as a Java object. My static main method consists of one line.
new InterestRateCalculator().run();
This line does two things. It creates an instance of the InterestRateCalculator class and it executes the run method of the class.
It may seem strange now, but getting away from static methods and static fields allows you to create complex Java applications with many, many classes. You should learn this now, while you're writing simple applications.
I implemented Runnable because a Runnable class requires a run() method. It's a personal preference of mine. You could have named the run() method execute(), or some other meaningful name.
I didn't write a constructor. I used the default constructor of InterestRateCalculator();
Looking now at the run() method, I divided the problem into two parts. Reading or getting the input and producing the output. This allows me to focus on a smaller, simpler problem than the original problem. This is called divide and conquer.
Getting the input is straightforward. I copied your code and made the prompt text consistent. I added a space at the end of each prompt so the prompts and responses would look better. I know this sounds silly, but I assure you that I spent the better part of my programming career making changes to the appearance of the input and output of applications.
Getting the output to line up took a large part of the code to produce the output. Producing the output was more complicated than gathering the input. I broke the process down into many methods. A method should do one thing, and return one output, like the calculateMonthlyPayment I showed you earlier.
I used a trick that I learned in the olden times of Cobol programming to produce the output. I left padded the Strings I created with spaces. You don't have to memorize this particular trick. Other "tricks" have been gathered together and called design patterns. Don't worry about learning any patterns right now. Just know that they exist so that you can group code into higher levels.
I hope this explanation was helpful to you. I know you wanted to write the code yourself. That's why I solved a different problem than yours.
monthpay is incorrect
monthPay = loan* rate/(1-1/(Math.pow(1+rate,years*12)))

Categories