Java Currency Converter (How to convert int to Double + Many other issues) - java

I'm struggling with finding the remainders when converting the currency and then dividing it into dollar amounts. Also, creating a minimum amount of currency to be converted is causing me an issue. I understand alot of my code is a mess but this is my first Java project. Any help would be much appreciated.
/* Currency Conversion
*/
import java.util.Scanner;//to get keyboard input from user
public class Currency {
/**
* Converts from a foreign currency to US Dollars. Takes a
* deduction for the transaction fee. Displays how many of
* each bill and coin denomination the user receives.
*
* #param args no parameters expected
*/
public static void main(String[] args)
{
final double SEK_CONVERSION_RATE = .14;
/*
* You'll need a variable or constant for the transaction fee.
* (3% is fairly typical.) You'll also need a variable or
* constant for the minimum transaction fee.
*/
double transactionFee = .03;
final double MIN_TRANSACTION_FEE = 10.00;
/*
* You're going to need a variable for the amount of that
* currency the user wants to convert.
*/
//Before you can ask the user for input, you need a Scanner so you can read
//that input:
Scanner keyboard = new Scanner(System.in);
/*
* Now you're ready to interact with the user. You'll want
* to greet them and let them know what currency they can convert
* and what the rate of exchange is.
*/
System.out.print("Hello there, welcome to your one and only stop for Swedish Krona conversions. The exchange rate currently sits at .14" );
/*
* You should also let them know about the transaction fee.
*/
System.out.println(" The minimum transaction fee is $10.00 USD.");
/*
* Now you're ready to prompt the user for how much money they
* want to convert.
*/
System.out.println("How many Swedish Krona would you like to convert to US Dollar?");
double userCurrencyInput = keyboard.nextDouble();
/*
* And then use the Scanner to read in that input and initialize your
* variable for currency:
*/
double calculatedCurrInput = (userCurrencyInput*SEK_CONVERSION_RATE);
/* setting up casting to use later in program */
int calculatedCurrInputInt = (int) (calculatedCurrInput);
/*
* You've received an amount in a foreign currency, but you're going
* to need the amount in dollars. Furthermore, you're going to need
* to know the number of 20's, 10's,5's, 1's, quarters, dimes, nickels
* and pennies. And you're going to need to know the transaction fee.
* These should all be stored in variables.
*/
double totalTransaction = (userCurrencyInput*transactionFee + calculatedCurrInput);
int totalTransactionInt = (int) (totalTransaction);
/*Need to define the remainder correct to make change*/
System.out.println("The conversion is " + calculatedCurrInput);
int twentyDollar = 20;
int twentyDollarBills = calculatedCurrInputInt/twentyDollar;
int remainderOfTwenty = calculatedCurrInputInt%twentyDollar;
int tenDollar = 10;
int tenDollarBills = remainderOfTwenty/tenDollar;
int remainderOfTen = remainderOfTwenty%tenDollar;
int fiveDollar = 5;
int fiveDollarBills = remainderOfTen/fiveDollar;
int remainderOfFive = remainderOfTen%fiveDollar;
int oneDollar = 1;
int oneDollarBills = remainderOfFive/oneDollar;
int remainderOfOnes = remainderOfFive%oneDollar;
double remainderOfOnesDBL = (double) remainderOfOnes;
double quarter = .25;
double numberOfQuarters = remainderOfOnesDBL/quarter;
double remainderOfQuarters = remainderOfOnesDBL%quarter;
double dimes = .10;
double numberOfDimes = remainderOfQuarters/dimes;
double remainderOfDimes = remainderOfQuarters%dimes;
double nickels = .05;
double numberOfNickels = remainderOfDimes/nickels;
double remainderOfNickels = remainderOfDimes%nickels;
double pennies = .01;
double numberOfPennies = remainderOfNickels/pennies;
/*
* Now you're ready to calculate the amount in USD.
*/
/*
* Determine what the transaction fee would be, based on the
* percentage.
*/
double totalTransactionFee = (userCurrencyInput*transactionFee);
System.out.println("The transcation fee for your currency exchange would be $" + totalTransactionFee + " US.");
/*
* If the transaction fee is less than the minimum transaction
* fee, you'll need to charge the minimum transaction fee.
* (Hint, the Math class has min and max methods that receive
* two numbers and return either the smaller or larger of those
* two numbers.)
*/
/*
* You'll need to deduct the transaction fee from the total.
*/
/*
* Calculate the number of $20's they'll receive
*/
/*
* How much is left?
*/
/*
* Next do the same for $10's, $5's, etc.
*/
/*
* Finally, let the user know how many dollars their foreign currency
* converted to, what was deducted for the transaction fee, and how
* many of each denomination they are receiving.
*/
System.out.println("The amount of 20's is " +twentyDollarBills);
System.out.println("The amount of 10's is " +tenDollarBills);
System.out.println("The amount of 5's is " +fiveDollarBills);
System.out.println("The amount of 1's is " +oneDollarBills);
System.out.println("The amount of quarters is " +numberOfQuarters);
System.out.println("The amount of dimes is " +numberOfDimes);
System.out.println("The amount of nickels is " +numberOfNickels);
System.out.println("The amount of pennies is " +numberOfPennies);
}//end main
}//end Currency

Firstly, you shouldn't be converting from doubles to ints, as you will lose the amount after the decimal point. e.g.
double num = 1.9;
int number = (int) num;
System.out.println(number);
will print
1
Also, if you do
System.out.println(num % 1);
you get
0.8999999999999999 // not quite 0.9, which is what you were expecting
As #Laf pointed out, use BigDecimal instead.
BigDecimal SEK_CONVERSION_RATE = new BigDecimal(".14");
String userInput = keyboard.nextLine();
// Better precision constructing from a String
BigDecimal userCurrencyInput = new BigDecimal(userInput);
BigDecimal calculatedCurrInput = userCurrencyInput.multiply(SEK_CONVERSTION_RATE);
Hopefully you can work out the rest from there.
Hint: BigDecimal has a method divideAndRemainder() which returns a BigDecimal[], where the first part is the quotient, and the second part is the remainder.
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

Related

The output shows zero, variable doesn't store the value

The main class:
package tdm;
import java.util.Scanner;
/**
*
* #author abbas
*/
public class TDM {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("** WHAT DO YOU WANT TO FIND? **");
System.out.println("1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame");
System.out.println("2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate");
System.out.println("3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame");
System.out.println("4. Find everything!!");
int choice;
System.out.println();
System.out.print("Enter your choice: ");
choice = input.nextInt();
switch (choice) {
case 1: {
Ex1 ex1 = new Ex1();
ex1.calculateEx1();
break;
}
}
}
}
The Ex1 class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package tdm;
import java.util.Scanner;
/**
*
* #author abbas
*/
public class Ex1 {
public void calculateEx1() {
Scanner input = new Scanner(System.in);
int connectionsNum, dataRate, bitMultiplexed;
System.out.print("Enter number of connections: ");
connectionsNum = input.nextInt();
System.out.print("Enter the data rate (Kbps) for each connection: ");
dataRate = input.nextInt();
System.out.print("Enter number of bit(s)");
bitMultiplexed = input.nextInt();
System.out.println("** Your question is **");
System.out.println("The data rate for each one of the " + connectionsNum
+ " connections is " + dataRate + " Kbps. If " + bitMultiplexed
+ " bit at time is multiplexed, what is (A) The duration of each"
+ " input slot, (B) duration of each output slot and (C) duration "
+ "of each frame");
System.out.println("** The answer is **");
int inputSlot = (bitMultiplexed / (dataRate * 1000));
int outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
System.out.println(inputSlot);
System.out.println(outputSlot);
System.out.println(frameDuration);
}
}
The output:
run:
** WHAT DO YOU WANT TO FIND? **
1. (A) Duration of each input slot, (B) Duration of each output slot and (C) Duration of each frame
2. (A) Input bit duration, (B) Output bit duration, (C) Output bit rate and (D) Output frame rate
3. (A) Duration of bit before multiplexing, (B) The transmission rate of the link, (C) The duration of a time slot and (D) The duration of a frame
4. Find everything!!
Enter your choice: 1
Enter number of connections: 3
Enter the data rate (Kbps) for each connection: 1
Enter number of bit(s): 1
** Your question is **
The data rate for each one of the 3 connections is 1 Kbps. If 1 bit at time is multiplexed, what is (A) The duration of each input slot, (B) duration of each output slot and (C) duration of each frame
** The answer is **
0
0
0
BUILD SUCCESSFUL (total time: 14 seconds)
As you can see, the three variables inputSlot, outputSlot and frameDuration should store the result of the expression. But as you can see in the output it shows 0. I think this is weird!! This is the first time something like this happen to me.
I suppose it's a small problem but I can't figure out what it's!!
The variables have to be floats instead of Integers. Integers can only store integers as the name sais. Floats can store point nubers like 0.0002. If u divide the int 20 by 11 and store this as a int Java will put 1 as the result. So if your result is 1.9 it is 1.0 as int. That is the Problem here. It looks like this
float inputSlot = (bitMultiplexed / (dataRate * 1000));
float outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
System.out.println(inputSlot);
System.out.println(outputSlot);
System.out.println(frameDuration);
If you have a question ask me :)
Enter the data rate (Kbps) for each connection: 1
Okay, so dataRate = 1.
Enter number of bit(s): 1
And bitMultiplexed = 1.
System.out.println(1 / (1000 * 1)); // 0
Need to cast to a float/double somehow, for example.
System.out.println(1 / (1000.0 * 1)) // 0.001
As you program/answer suggests.
inputSlot = 1 / 10000 = 0;
output = (1/3)*0 = 0;
frameDuration = 3 * 0 = 0;
Since these are int. It will strip the decimal part. Use BigDecimal or double for this purpose
The problem arises due to these 3 fields being initialized as ints. If you make them double your problem will be solved because when you declare them as ints, it will take just the integer part. So for example if you have 0.588 it will take just the 0 which is what is happening as of now.
int inputSlot = (bitMultiplexed / (dataRate * 1000));
int outputSlot = ((1 / connectionsNum) * inputSlot);
int frameDuration = (connectionsNum * outputSlot);
In order to solve this, you need to change the int to double.

Java: method not returning to main

In Java for some reason the averageSpeed method is not returning a double value or any value. It seems that the method never exits back to the main method for some reason. I do not understand why this happens.
The values I input are accordingly 0, 30, 14, 15, 14, 45. I expect the double 60.0 to be returned.
import java.util.Scanner;
/**
* Auto Generated Java Class.
*/
public class CarSpeed {
/**
* Computes a car's average speed over the legnth of a trip.
*
* #param milesStart odometer reading at the start of the trip
* #param milesEnd odometer reading at the end of the trip
* #param hrsStart hours on the (24 hour) clock at the start
* #param minsStart minutes on the clock at the start
* #param hrsEnd hours on the (24 hour) clock at the end
* #param minsEnd minutes on the clock at the end
* #return the average speed (in miles per hour)
*/
public static double averageSpeed(double milesStart, double milesEnd,
double hrsStart, double minsStart, double hrsEnd, double minsEnd) {
double distanceTraveled;
double minutes;
double hours;
double sixty;
double minuteHours; //minutes converted into hours
double time;
double averageSpeed;
distanceTraveled = milesEnd - milesStart;
minutes = minsEnd - minsStart;
sixty = 60;
minuteHours = minutes/sixty;
hours = hrsEnd - hrsStart;
time = minuteHours + hours;
averageSpeed = distanceTraveled/time;
return averageSpeed;
}
/**
* #param args
*/
public static void main(String[] args) {
double milesStart;
double milesEnd;
double hrsStart;
double minsStart;
double hrsEnd;
double minsEnd;
Scanner input = new Scanner(System.in);
System.out.print("What is the odometer reading at the start of the trip?");
milesStart = input.nextDouble();
System.out.print("What is the odometer reading at the end of the trip?");
milesEnd = input.nextDouble();
System.out.print("What is the hours on the 24 hr clock at the start?");
hrsStart = input.nextDouble();
System.out.print("What is the minutes on the clock at the start?");
minsStart = input.nextDouble();
System.out.print("What is the hours on the 24 hr clock at the end?");
hrsEnd = input.nextDouble();
System.out.print("What is the minutes on the clock at the end?");
minsEnd = input.nextDouble();
averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd);
}
}
You dont see any value, because you didnt even store it. It should work good, but you should edit last line from averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd); to System.out.println(averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd));. Then you will be able to display returned variable.
If the method has a return value, you must create an Object to save it.
Double avgSpeed = averageSpeed(milesStart, milesEnd, hrsStart, minsStart, hrsEnd, minsEnd);
System.out.println("Average Speed is " + avgSpeed);
Remember that returning a value does not mean printing it. You can assign the returned double to some variable like:
double result = yourFunction(arg1, arg2, arg3, arg4, arg5, arg6);
And then you can print it out to the console:
System.out.println(result);
The second option is printing it out straight away from the function:
System.out.println(yourFunction(arg1, arg2, arg3, arg4, arg5, arg6));

Nickles in Coin Counter not displaying correct amount

I was just given my first assignment in my Java class, and we were tasked with creating a program that counts nickles and displays the total amount of money. However, whenever I put an odd number of nickles it does not display the corrent amount of money. For example, 1 nickles turns into $.5 instead of $.05. 21 Nickles turns into $1.5 instead of $1.05. I'm asumming this is an easy fix for an easy problem, but I am finding myself stumped. Thanks for the help.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
int nickles5 = nickles * 5;
int dollars = nickles5 / 100;
int change = nickles5 % 100;
System.out.println("You have $" + dollars + "." + change);
}
I'll go out on a limb here, to try to solve your problem. It appears that you will ask the user to enter some number of nickels, and you will output the amount in dollars. Please let me know if this is incorrect in any way.
Now look at the following code.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();
double nickles5 = nickles * 0.05;
System.out.println("You have $" + nickles5);
}
After we have the number of nickels stored in an int, we multiply it by 0.05, to get the actual value of all the nickels. We store this in a double variable [Note: int multiplied to a double, returns a double; it is called numeric promotion]. Now, to get the total value, you can simply print this double variable. In a case where n=2, nickels5 = 0.1. So, it will print $0.1
If you want this to show up as $0.10, simply replace the nickels5 with String.format( "%.2f", nickels5)
Now your final line will look like:
System.out.println("You have $" + String.format( "%.2f", nickels5));
Let me know if this solved your issue.
You need to format change to use 2 digits, rather than just printing out the raw number. Specifically, if change==5, you want to print out 05.
You can do this with String.format("%02d", change)
You have a random apostrophe at the end, why?
You want to use floats instead of ints, like this:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
System.out.println("$"+ amount);
Output:
Deposit your Nickles.
1
$0.05
Deposit your Nickles.
21
$1.05
EDIT: Code with formatted output:
Scanner in = new Scanner(System.in);
int nickles;
System.out.println("Deposit your Nickles.");
nickles = in.nextInt();//get number
float nickles5 = nickles * 5;//input 1, get 5
float amount = nickles5/100;
String output = String.format("%02f", amount);//f(loat) not d
System.out.println("$"+ output);

How to round to the nearest cent in Java

So I am writing a program that does some financial calculations. However, because I used double for my data types, the cents are not rounded. Here is the source code:
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
System.out.println("Principle: $" + principle);
System.out.println("Annual Rate: " + annualRate + "%");
System.out.println("Number of years: " + numYears);
System.out.println("Monthly Payment: $" + monthlyPayment);
System.out.println("Total Payments: $" + totalPayment);
System.out.println("Total Interest: $" + totalInterest);
}
}
My instructor also does not want this to use the DecimalFormat class. I was thinking to obtain the cents value by doing: variable-Math.floor(variable), and then rounding that amount to the nearest hundredth, then adding that together.
Without using the JDK-provided library classes that exist for this purpose (and would normally be used), the pseudocode for rounding arithmetically is:
multiply by 100, giving you cents
add (or subtract if the number is negative) 0.5, so the next step rounds to the nearest cent
cast to int, which truncates the decimal part
divide by 100d, giving you dollars)
Now go write some code.
Well, if you cannot use the DecimalFormat class, you could use printf():
TextLab03, Student Version
Principle : $259,000.00
Annual Rate : 5.75%
Number of years : 30.00
Monthly Payment : $1,511.45
Total Payments : $544,123.33
Total Interest : $285,123.33
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
printAmount("Principle", principle);
printPercent("Annual Rate", annualRate);
printCount("Number of years", numYears);
printAmount("Monthly Payment", monthlyPayment);
printAmount("Total Payments", totalPayment);
printAmount("Total Interest", totalInterest);
}
public static void printPercent(String label, double percentage) {
//System.out.printf("%-16s: %,.2f%%%n", label, percentage);
printNumber(label, percentage, "", "%", 16);
}
public static void printCount(String label, double count) {
//System.out.printf("%-16s: %,.2f%n", label, count);
printNumber(label, count, "", "", 16);
}
public static void printAmount(String label, double amount) {
//System.out.printf("%-16s: $%,.2f%n", label, amount);
printNumber(label, amount, "$", "", 16);
}
public static void printNumber(String label, double value, String prefix, String suffix, int labelWidth) {
String format = String.format("%%-%ds: %%s%%,.2f%%s%%n", labelWidth);
System.out.printf(format, label, prefix, value, suffix);
}
}

determine the periodic loan payment

am not getting this program to display my instalments correctly can I please get some help thanks......
package Loops;
import java.util.Scanner;
/**
*
*
*/
public class program {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//variabled decleared
double rate;
double payment;
//input
System.out.print("Enter Loan Amount:");
double principal = input.nextDouble();
System.out.print("Enter Annual Interest:");
double interest = input.nextDouble();
System.out.print("Total payments per year:");//12=monthly,4= quartely,2=semi-annually and 1=annually
double period = input.nextDouble();
System.out.print("Enter Loan Length :");
int length = input.nextInt();
//proces
double n = period * length;
rate = interest / 100;
double monthly_rate = rate / period;
payment = principal * (principal * (monthly_rate * Math.pow((1 + monthly_rate), n)));
System.out.printf("Your Monthly sum is %.2f", payment);
}
}
principal = 50000; //Redacted. Eating my words.
period = 4;
length = 4;
n = 16;
rate = 0.085;
monthly_rate = 0.085 / 16 = 0.0053125;
payment = 50000 * 50000 * 0.0053125 * (1 + 0.0053125) ^ 16;
= 2.5x10^9 * 0.0053125 * 1.088;
= Something remainingly massive
Basically... your formula is wrong. Wouldn't you need to divide by the power quotient? Where is your source on that formula?
payment = principal * (rate + (rate / ( Math.pow(1 + rate, n) - 1) ) );
Source
Example:
payment = 50000*(0.085+(0.085/(1.085^16-1)))
= 5830.68
Try this for your formula:
//this is how much a monthly payment is
payment = (rate + (rate / ((Math.pow(1 + rate), n) -1)) * principal
This is based off one of the first google results for the formula. Please post the results and expected answer if it is wrong.
I'm pretty sure your formula is just off, as you stated above that there should be a denominator in the equation.
You can use r* Math.pow ((1+r),n) to calculate the numerator and part of the denominator

Categories

Resources