Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am having two problems with my code.
First: I can't seem to add "$" in the right location (I cant get it to look like $10.00 only 10.00$)
Second: Adding a Scanner class ends up with the program "running" but nothing happening. (if I set gross with a number it runs fine but not with using a scanner class)
import java.util.Scanner;
public class Payment
{
public static void main(String[] args)
{
Scanner Keyboard = new Scanner(System.in);
//double gross = Keyboard.nextDouble(); will not work
//double gross = 8000; will work
double fed = (0.15 * gross);
double state = (0.035 * gross);
double soc = (0.0575 * gross);
double med = (0.0275 * gross);
double pen = (0.05 * gross);
double hea = 75;
double net = (gross - (fed + state + soc + med + pen + hea));
System.out.println("Paycheck calculation by employee\n");
System.out.printf("Gross Amount:%28.2f%n", gross);
System.out.printf("Federal Tax:%29.2f%n", fed);
System.out.printf("State Tax:%31.2f%n", state);
System.out.printf("Social Security Tax:%21.2f%n", soc);
System.out.printf("Medicare/Medicaid Tax:%19.2f%n", med);
System.out.printf("Pension Plan %28.2f%n", pen);
System.out.printf("Health Insurance %24.2f%n%n", hea);
System.out.printf("Net Pay:%33.2f", net);
}
}
You probably want to print out an input prompt. Regarding currency formatting, you could use the DecimalFormat class.
import java.text.DecimalFormat;
import java.util.Scanner;
public class Payment
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter gross amount: ");
double gross = keyboard.nextDouble();
//double gross = 800; //will work
double fed = (0.15 * gross);
double state = (0.035 * gross);
double soc = (0.0575 * gross);
double med = (0.0275 * gross);
double pen = (0.05 * gross);
double hea = 75;
double net = (gross - (fed + state + soc + med + pen + hea));
DecimalFormat currency = new DecimalFormat("$0.00");
System.out.println("Paycheck calculation by employee\n");
System.out.printf("Gross Amount: %27s%n", currency.format(gross));
System.out.printf("Federal Tax:%29s%n", currency.format(fed));
System.out.printf("State Tax:%31s%n", currency.format(state));
System.out.printf("Social Security Tax:%21s%n", currency.format(soc));
System.out.printf("Medicare/Medicaid Tax:%19s%n", currency.format(med));
System.out.printf("Pension Plan %28s%n", currency.format(pen));
System.out.printf("Health Insurance %24s%n%n", currency.format(hea));
System.out.printf("Net Pay:%33s", currency.format(net));
keyboard.close();
}
}
Answering your first question, you could it like this:
System.out.printf("Gross Amount %28c%.2f%n", '$', gross);
Your second question, i think your problem is the Locale. Depending on your Locale, the input format of a Double, in this case, may be different. You could do:
keyboard.useLocale(Locale.US);
This way, the input of a Double will be the integer part separated by a . from the decimal part. 8000 and 5.5 are valid examples of a Double input.
Related
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 do the calculations for the interest in another method, and I know that I have to make another method outside of main and then put return an the end, but I have no idea what to title this new method and how to go about doing the calculations there. I think it is the while loop that is confusing me. I have done this once before on a different project, so I have an idea of how to do it, but this project isn't anything like the other one and I don't really understand it. Any help is extremely appreciated as I have been working on this for a long time and just want to get it over with. Thanks in advance.
import java.util.Scanner; // This allows for the use of the scanner in the class
public class SavingsAccount // Start of class
{
public static void main(String[]args) // Start of main
{
double P; // These store the amounts that will be used in the accruing interest formula
double i;
double n;
double S = 0;
int timesLooped = 0;
Scanner readConsole = new Scanner(System.in); // This is the scanner
System.out.println("I am a savings account interest calculator."); // Prompts the user for input
System.out.println("How much money have you deposited?");
P = readConsole.nextDouble();
S = P;
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
i = readConsole.nextDouble();
System.out.println("Finally, how long do you plan on having the money in the account?");
n = readConsole.nextDouble();
while (timesLooped <= n)
{
S = S + (P * i);
timesLooped += 1;
}
System.out.println("Your balance in that time span is " + S + "."); // Tells you your ending balance
}
}
Based on your comment, I think you want this:
private static double addInterest(double S, double P, double i)
{
return S + (P * i);
}
...
public static void main()
{
...
while (timesLooped <= n)
{
S = addInterest(S, P, i);
}
EDIT
I made some small improvements just for fun:
I put the entire interest calculation into the function and used exponentiation rather than a loop.
I gave the variables more descriptive names.
I used System.out.format to print the result.
Here's the code:
private static double computeCompoundInterest(double principal, double rate,
double years) {
return principal * Math.pow(1 + rate, years);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("I am a savings account interest calculator.");
System.out.println("How much money have you deposited?");
double principal = scanner.nextDouble();
System.out.println("Now, what is the annual interest rate? (i.e. .05)");
double rate = scanner.nextDouble();
System.out.println("How many years will you hold that money in the account?");
double years = scanner.nextDouble();
double total = computeCompoundInterest(principal, rate, years);
System.out.format("Your balance at the end of that period will be %.2f.\n", years, total);
}
So I'm a beginner which you can probably tell and I am currently trying to understand parameters and was wondering if I did this correctly. The program works but I didn't want to have it formatted wrong or maybe I used them for no reason since the arguments(?) don't change. We are currently studying parameters so I figured I'd give it a shot and try to include it in this assignment.
import java.util.Scanner;
public class Investments
{
public static void main(String []args)
{
double investment,interestRate, futureValue;
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the investment amount?");
investment = keyboard.nextDouble();
System.out.println("What is the interest rate?");
interestRate=keyboard.nextDouble();
futureValue = investment * (Math.pow(1+interestRate, 5));
futureValue = investments(futureValue);
System.out.println("Your investment afer 5 years:" + futureValue);
futureValue = investment * (Math.pow(1+interestRate, 10));
futureValue = investments(futureValue);
System.out.println("Your investment after 10 years:" + futureValue);
futureValue = investment * (Math.pow(1+interestRate, 20));
futureValue = investments(futureValue);
System.out.println("Your investment after 20 years:" + futureValue);
}
public static double investments (double futureValue)
{
double result;
result = Math.round(futureValue * 100);
result = result/100;
return result;
}
}
That looks pretty good! If you want to make your investments function even more powerful you can move all the logic into there, and just pass in the investment, interest rate and investment period.
public static double investments (double investment, double interestRate, int numYears)
Then your main function can just be:
futureValue = investments(interestRate, 5);
System.out.println("Your investment after 5 years:" + futureValue);
futureValue = investments(interestRate, 10);
System.out.println("Your investment after 10 years:" + futureValue);
(etc)
Im new to java and practising my coding, how would I write some Junit tests for this code without changing it? I wanted to write some Junits to see if the output is correct. Could someone provide one such example?
Any help is greatly appreciated.
package returnOnInvestment;
import java.util.Scanner;
/**
This program compares CD /Investment plans input by the year
broken down by the requirements below:
This program creates a table of compound interest investment growth over time
Broken down by: a) year b) balance at end of year
Finance formula of A= P(1+ r/n)^n*t is used:
A = Future Value | P = Initial Investment
r = annual interest rate |n = times interest is compounded/year
t = years invested
*/
public class BestInvesment
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String bestBankName = "";
double bestGrowth = 0;
boolean done = false;
while(!done)
{
System.out.print("Plan name (one word, Q to quit): ");
String bankName = in.next();
if (bankName.equals("Q"))
{
done = true;
}
else
{
System.out.print("Please enter your principal investment: ");
final double PRINCIPAL_INVESTMENT = in.nextDouble();
System.out.print("Please enter the annual interest rate: ");
double iRate = in.nextDouble();
System.out.print("Please enter number of times interest is compounded per year: ");
final double INCREMENT = 1;//in.nextDouble();
System.out.print("Enter number of years: ");
int nyears = in.nextInt();
iRate = iRate/100; System.out.println("iRate:" + iRate);
//Print the table of balances for each year
for (int year = 1; year <= nyears; year++)
{
double MULTIPLIER = INCREMENT * year;
System.out.println("Multiplier: " + MULTIPLIER); // I've included this print statement to show that the multiplier changes with each passing year
double interest = 1 + (iRate/INCREMENT);
double balance = PRINCIPAL_INVESTMENT;
double growth = balance * Math.pow(interest, MULTIPLIER);
growth = growth - PRINCIPAL_INVESTMENT;
balance = balance + growth;
System.out.printf("Year: %2d Interest Earned: $%.2f\t Ending Balance: $%.2f\n", year, growth, balance);
if (bestBankName.equals("") || bestGrowth > growth) // || bestBankName > growth
{
bestBankName = bankName; // bestBankName = bankName
bestGrowth = growth; // mostGrow = growth
}
System.out.println("Earning with this option: " + growth);
}
}
}
System.out.println("Best Growth: " + bestBankName);
System.out.println("Amount Earned: " + bestGrowth);
}
}
As it is, this code is very difficult to test, which it is a symptom of some design smells.
One thing to realize is that you are severely violating the Single Responsibility Principle.
Your code which is just one blob is doing the following things:
printing stuff to console
getting input from the user
doing some calculation
coordinating all this
Since this is in the realm of practicing, I would heavily refactor the code into separate classes. Those then should be easily testable, especially the one doing the calculation, since it will have just some simple methods where you can pass some values as arguments, and check the results
For testing the input and output classes note that you can change System.in and System.out to point to your own implementations, so you can create those to facilitate testing. You might want to look into a mocking framework for this (e.g. Mockito) but it is perfectly possible without such framework.
Can anybody tell me what I am doing wrong here. I need to calculate some values from user-input into some JOptionPane-input-dialog-boxes, then outputting the answers.
I would greatly appreciate any help I get. Thanks In Advance!
Input
Number of loans to compare (Could be more than 1)
Selling price
Down payment
You will ask the following for each loan they want to compare
Interest rate
Number of years
Processing
You will need to calculate the monthly payment for each scenario listed in part d for the given interest rates and number of years.
Output
Selling price
Down Payment
Loan Amount
List for each scenario
interest
years
payment
Here's my code so far:
package javamortgagecalculator;
import javax.swing.JOptionPane;
import java.util.*;
public class JavaMortgageCalculator {
public static void main(String[] args) {
//A. Enter the Number Of Loans to compare
String numberOfLoansString = JOptionPane.showInputDialog("Enter the Number Of Loans to Compare");
//Convert numberOfLoansString to int
int numberOfLoans = Integer.parseInt(numberOfLoansString);
//B. Enter the Selling Price of Home
String sellingPriceString = JOptionPane.showInputDialog("Enter the Loan Amount");
//Convert homeCostString to double
double sellingPrice = Double.parseDouble(sellingPriceString);
//C. Enter the Down Payment on the Home
String downPaymentString = JOptionPane.showInputDialog("Enter the down payment on the Home");
double downPayment = Double.parseDouble(downPaymentString);
//Get the loanAmount by Subtracting the Down Payment from homeCost
double loanAmount = sellingPrice - downPayment;
//D. Ask the following for as many number of loans they wish to compare
//D1 Get the interest rate
double[] annualInterestRatesArray = new double[numberOfLoans];
double[] monthlyInterestRateArray = new double[numberOfLoans];
int[] numberOfYearsArray = new int[numberOfLoans];
double[] monthlyPaymentArray = new double[numberOfLoans];
double[] totalPaymentArray = new double[numberOfLoans];
int counter = 1;
for (int i=0; i < numberOfLoans; i++)
{
String annualInterestRateString = JOptionPane.showInputDialog("Enter the interest rate for Scenario " + counter);
double annualInterestRate = Double.parseDouble(annualInterestRateString);
annualInterestRatesArray[i] = (annualInterestRate);
//Obtain monthly interest rate
double monthlyInterestRate = annualInterestRate / 1200;
monthlyInterestRateArray[i] = (monthlyInterestRate);
//D2 Get the number of years
String numberOfYearsString = JOptionPane.showInputDialog("Enter the number of years for Scenario " + counter);
int numberOfYears = Integer.parseInt(numberOfYearsString);
numberOfYearsArray[i] = (numberOfYears);
//Calculate monthly payment
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12));
//Format to keep monthlyPayment two digits after the decimal point
monthlyPayment = (int)(monthlyPayment * 100) / 100.0;
//Store monthlyPayment values in an array
monthlyPaymentArray[i] = (monthlyPayment);
//Calculate total Payment
double totalPayment = monthlyPaymentArray[i] * numberOfYears * 12;
//Format to keep totalPayment two digits after the decimal point
totalPayment = (int)(totalPayment * 100) / 100.0;
totalPaymentArray[i] = (totalPayment);
counter++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfLoans; i++) {
sb.append(String.format("\t \t \t \t \t \n", sellingPrice, downPayment, loanAmount, Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray)));
}
String toDisplay=sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
}
}
If I was forced, presumably by a large green, and particularly ugly troll masquerading as a programming teacher, to use multiple JOption panes for input and output then here's how I'd tackle the problem. This is meant for your information only... if you hand this in as your own work your teacher will smell a rat, and trolls have google too.
package forums;
import javax.swing.JOptionPane;
import java.text.DecimalFormat;
/**
* Compares total cost of mortgages (aka ordinary annuity certains)
*/
public class MortgageCalculator
{
public static void main(String[] args)
{
// 1. input
final double price = Enter.aDouble("the purchase of the property");
final double deposit = Enter.aDouble("down payment");
Loan.setPrinciple(price - deposit);
int numLoans = Enter.anInteger("number of loans to compare");
Loan[] loans = new Loan[numLoans];
for ( int i=0; i<numLoans; ++i ) {
loans[i] = new Loan(
Enter.aDouble("Annual interest rate for Loan " + (i+1) + " (eg: 6.75)") / 100.0 / 12.0
, Enter.anInteger("number of years for Loan " + (i+1) + " (eg 20)") * 12
);
}
// 3. Output
final String caption =
"Principle " + Format.money(Loan.getPrinciple())
+ " = Price " + Format.money(price)
+ " - Deposit " + Format.money(deposit);
StringBuilder results = new StringBuilder(64 + numLoans * 64);
results.append("Monthly Rate, Months, Monthly Repayment, Total Repayments\n");
for ( Loan l : loans ) {
results.append(String.format("%5s, %d, %13s, %13s\n"
, Format.percent(l.rate)
, l.periods
, Format.money(l.payment())
, Format.money(l.totalPayment())
));
}
JOptionPane.showMessageDialog(null, results.toString(), caption, JOptionPane.INFORMATION_MESSAGE);
}
static class Format
{
static java.text.Format MONEY = new DecimalFormat("$#,###.##");
static String money(double amount) {
return MONEY.format(amount);
}
static java.text.Format PERCENT = new DecimalFormat("0.###%");
static String percent(double amount) {
return PERCENT.format(amount);
}
static StringBuilder join(String between, Object... values) {
StringBuilder result = new StringBuilder(values.length * 16);
if ( values.length > 0 ) {
result.append(values[0].toString());
for ( int i=1; i<values.length; ++i ) {
result.append(between)
.append(values[i].toString());
}
}
return result;
}
} // end class Format
static class Enter
{
public static int anInteger(String fieldDesc) {
return Integer.parseInt(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
public static double aDouble(String fieldDesc) {
return Double.parseDouble(JOptionPane.showInputDialog("Enter the "+ fieldDesc));
}
} // end class Enter
} // end class MortgageCalculator
class Loan
{
private static double principle = 34324.121221312432;
final double rate;
final int periods;
static void setPrinciple(double principle) {
if (Loan.principle != 34324.121221312432)
throw new ReadOnlyException("The Principle can't be changed once set.");
Loan.principle = principle;
}
static double getPrinciple() {
return Loan.principle;
}
/**
* Initialises a new loan objects
* #param double rate The interest rate per period, as a percentage.
* eg: 0.00625 is 7.5% per annum.
* #param int periods The number of periods of the loan, typically months.
*/
Loan(double rate, int periods) {
this.rate = rate;
this.periods = periods;
}
// 2. processing
double payment() {
return principle * rate / (1 - 1/Math.pow(1+rate,periods) );
}
double totalPayment() {
return periods * payment();
}
}
class ReadOnlyException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public ReadOnlyException(String message) {
super(message);
}
}
The "list of loans to compare" is represented by an array of Loan objects... I.e: each "loan option" is represented by an instance of the Loan class, which groups all the attributes of a particular loan into one nice tidy "thing" which we can then manipulate as a whole. This a better appraoch than the technique you're using to store loan attributes, which is called "parallel arrays"... and well, umm, it's a bit outdated, in-fact it's got a (greasy) mullet, it's wearing a (too tight) orange safari suit with a (safron pink) head-band... It wasn't a good look in the eighties, and these days, well it's likely to get you beaten-up, arrested, or both; depending on your locale... Basically: We have have better ways now!
The Loan class also has a couple of handy "calculated fields" to do the computations for us. This means that if the WAY we calculate repayments changes for some reason in future, we only have one place to change it, and everything that uses Loans (which could be reading, writing, permuting, totalling, repossessing, or even wholesaling loans) does NOT have to change... they just pick up the change "for free".
In this contrived use-case all our Loans will be for the same ammount, only the interest rates and periods vary... so the Loan class also has a static variable called "principle", which holds THE "common" principle for ALL instances of the Loan class. The principle may only be set once. Any subsequent attempt to set the prinicple will cause a ReadOnlyException to be thrown.
Anyway, I hope that you learn something from seeing another way to tackle some of the sub-problems you may have dicovered while doing this exercise yourself. One tip for the future: Grab your class-mates code for this exercise and read through it... you can learn a LOT from how other people tackle things.
Cheers. Keith.
Now you need to examine the result returned by showMessageDialog(), as shown here.
String.format("\t \t \t \t \t \n", sellingPrice, ...
That's just going to output 5 tabs. You want
String.format("%s %s %s %s %s %n", sellingPrice, ...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ Arrays.toString(annualInterestRatesArray), Arrays.toString(numberOfYearsArray), Arrays.toString(monthlyPaymentArray));
}
You haven't told us what the problem is, but I don't think this bit is doing what you want. You're asking the program to print out the entirety of your three arrays every time the loop goes round. Instead, you probably want to access the specific array element for each loan, right? Something like...
for (int i = 0; i < numberOfLoans; i++)
{
sb.append(/*...snip...*/ annualInterestRatesArray[i], numberOfYearsArray[i], monthlyPaymentArray[i]);
}
Your JOptionPane.showMessageDialog(null... is inside a for loop. So it will show it as many times as the value of numberOfLoans2 . If you dont want that, move your
String toDisplay = sb.toString();
JOptionPane.showMessageDialog(null, sb.toString(), toDisplay, JOptionPane.INFORMATION_MESSAGE);
outside the for-loop.
In your answer printing method the numberOfLoans2 variable is used in two places: in a for loop making the printing happen many times (outer loop) and in a for loop making the mathematic calculation (inner loop). Probably the outer one is with no use, so remove it and the result may be shown once. Remember to remove the ending } on the end of the loop element to keep the structure ok :)