Describe the algorithm of currency conversion - java

CurrencyConversion that offers the user the choice of converting US Dollars into British Pounds or the other way around. (You may assume that 1 US Dollar = 1.64 Pounds.)
// Import scanner
import java.util.Scanner;
public class MoneyConversion {
public static void main (String[] args) {
// Declare variable
final double RATE = 1.64;
// Declare currency
double dollar;
double Pounds;
// Call scanner from keyBoard
Scanner fromKeyboard = new Scanner(System.in);
// Ask user to enter the amount of pounds
System.out.print("Please write number of pounds");
// Read the value into variable
Pounds = fromKeyboard.nextDouble();
// Write the method for currency conversion
dollar = Pounds * RATE;
System.out.println("The number of dollars is " + dollar);
} // End of main
} // End currency conversion

Make different classes for different currency conversions as follows:
public static void main(String[] args) {
Scanner fromKeyboard = new Scanner(System.in);
System.out.print("Please write number of pounds");
System.out.println("The number of dollar is " + convertToDollar(fromKeyboard.nextDouble()));
}
public static double convertToDollar(double pound){
double rate = 1.64;
double Pounds;
return( pound * rate);
}

Related

why "Keyboard.readDouble()" doesn't work?

All I want it to do is read input typed by the user as double type, and then convert it to another number. I'm also aware the equation isn't complete, not worried about that right now, just want it to run. I don't understand what I have done wrong.
public class EuroShoe {
public static void main(String[] args) {
double
footLength,
euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
footLength = Keyboard.readDouble(); // line 25
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
If you are following a tutorial, please check on the imports that were mentioned. But to answer your question and make your program work here's an answer.
import java.util.Scanner
public class EuroShoe {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i =
double footLength, euroSize;
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
// The statement below calls the "scanner" object to get the user input of value "double"
footLength = scanner.nextDouble();
euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}
Make sure to put this statement above
import java.util.Scanner // imports the specific Scanner class under the 'util' namespace
or you can use this as well
import java.util.* // imports every class under the 'util' namespace
Hope this helps you with your problem and keep coding! :)
This worked:
package euroshoe;
import java.util.Scanner;
public class EuroShoe {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("EUROPEAN SHOE SIZE");
System.out.println("Enter the length of your foot in inches:");
double footLength = input.nextDouble();
double euroSize = (((footLength - 9) * 3 / 2) + 15);
System.out.println("Your European shoe size is " + euroSize);
}
}

Java compiler is telling me I have not initiated variable "interest" or "pmt"

I am trying to program an amortization calculator in which the user can enter a value for balance, a value for their interest rate in decimal form, and a value for monthly payment. With this information I want to output an interest amount in dollars, a principal amount, and a new balance. Here is my code:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner pmt, interest, balance = new Scanner(System.in);
System.out.println("What is your balance?");
double b = balance.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = interest.nextDouble();
System.out.println("What is your monthly payment?");
double p = pmt.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
You should not declare 3 scanners to read from the standard input. Declare one and just keep reading from it. Like this:
import java.util.Scanner;
public class Amortization{
public static void main(String []args){
Scanner input = new Scanner(System.in);
System.out.println("What is your balance?");
double b = input.nextDouble();
System.out.println("What is your interest rate in decimal?");
double i = input.nextDouble();
System.out.println("What is your monthly payment?");
double p = input.nextDouble();
double pv = p-(b*i);
System.out.println("Your interest amount is " + (b*i));
System.out.println("Your principal amount is " + pv);
System.out.println("Your new balance is " + (b-pv));
}
}
The main point here is that a scanner is the object that reads from an input stream, not the value being read. You don't need a new scanner for every value you want to read.
As #nhouser9 says, you don't need three scanners and answering your question the compiler says that the variables are not initialized because you are only initializing the last of them (balance). Multiple initializing in java won't functions as you expected (initialize all the variables with the same value).

Java Program Loop

i want to be able to have the program to start over (show the enter loan amount prompt) after typing 'y' when asked "to calculate the program again" or end program if user input 'n'.
import java.util.Scanner;
public class MonthlyMortgageRate {
public static void main(String[] args) {
double Amount;
double Rate;
double Months;
double outputNum1;
Scanner in = new Scanner(System.in);
System.out.print("Enter loan amount:");
Amount = in.nextDouble();
System.out.print("Enter rate:");
Rate = in.nextDouble() / 100 / 12;
System.out.print("Enter year:");
Months = in.nextDouble() * 12;
outputNum1 = Rate * Amount / (1 - Math.pow(1 + Rate, -Months));
if (Amount <= 0)
System.out.println("You must enter positive numeric data!");
else
System.out.printf("Monthly payment is: $ %.2f%n", outputNum1);
System.out.println("would you like to calculate again?(y/n)");
}
private static double inputNum2(double d) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Basically you need to loop the code in main.
do {
// your code here
System.out.println("would you like to calculate again?(y/n)");
} while (in.next().equalsIgnoreCase("y"))
Add the following to your code:
Boolean doagain = true;
// after Scanner in
while(doagain)
{
// your code
System.out.println("would you like to calculate again?(y/n)");
if ( in.next().toLowerCase().equals("n") ) doagain = false;
} // end while
// your code
Enjoy Cliff

Calling a method adding input

I'm having problems finding out how to get the output based on the user inputs for my Main class. I already have keyboard entry where the users can enter a value, which will be held. I'm guessing I will need to use that e.g. (input.input1());. However I also need to include the method which calculates the result e.g calculations.theAverageMassFfTheVehicle from the CalculatingRocketFlightProfile class, I'm just not sure how to combine the two to get the result.
//Calculations class
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
public double averageImpulse;
public double timeEjectionChargeFires;
public double massEmptyVehicle;
public double engineMass;
public double fuelMass;
//Declaring variables for outputs
public double theAverageMassOfTheVehicle;
public double theVehiclesMaximumVelocity;
public CalculatingRocketFlightProfile(double totalImpulse, double averageImpulse, double timeEjectionChargeFires, double massEmptyVehicle,
double engineMass, double fuelMass) { //Constructor for this class
this.totalImpulse = totalImpulse;
this.averageImpulse = averageImpulse;
this.timeEjectionChargeFires = timeEjectionChargeFires;
this.massEmptyVehicle = massEmptyVehicle;
this.engineMass = engineMass;
this.fuelMass = fuelMass;
}
//Mutators and Accessors
//Accessors
//Methods for calculations - Calculating outputs, using inputs.
public double theAverageMassOfTheVehicle() {
return massEmptyVehicle + ((engineMass + (engineMass - fuelMass) )/ 2); //Formula to calculate Average mass
}//method
public double theVehiclesMaximumVelocity() { //Formula to calculate Maximum velocity
return totalImpulse / getTheAverageMassOfTheVehicle();
}//method
//Returns - GET
public double getTheAverageMassOfTheVehicle() {
return theAverageMassOfTheVehicle;
}//method
public double getTheVehiclesMaximumVelocity() {
return theVehiclesMaximumVelocity;
}//method
}//class
//Main class
public class Main { //Master class
public static void main( String args[] ) //Standard header for main method
{
kbentry input = new kbentry();
System.out.print("\nPlease enter a number for Total Impulse: " );
System.out.println("You have entered : " +input.input1());
System.out.print("\nPlease enter a number for Average Impulse: " );
System.out.println("You have entered : " +input.input2());
System.out.print("\nPlease enter a number for Time ejection charge fires: " );
System.out.println("You have entered : " +input.input3());
System.out.print("\nPlease enter a number for the Mass of the vehicle: " );
System.out.println("You have entered : " +input.input4());
System.out.print("\nPlease enter a number for the Mass of the engine: " );
System.out.println("You have entered : " +input.input5());
System.out.print("\nPlease enter a number for the Mass of the fuel: " );
System.out.println("You have entered : " +input.input6());
//Output
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.println("\nThe average mass of the vehicle: " +calculations.theAverageMassOfTheVehicle() +
"\nThe vehicles maximum velocity: " + calculations.theVehiclesMaximumVelocity());
}
}
//kbentry
public class kbentry{
double input1(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//Total Impulse entry
String strTotalImpulse = null; // These must be initialised
int intTotalImpulse = 0;
//System.out.print("Please enter a number for Total Impulse: ");
//System.out.flush();
// read string value from keyboard
try {
strTotalImpulse = in.readLine();
}
catch (IOException ioe) {
// ignore exception
}
// convert it to integer
try {
intTotalImpulse = Integer.parseInt(strTotalImpulse);
}
catch (NumberFormatException nfe) {
System.out.println("Error! Please enter a number!" + nfe.toString());
}
The problem is that you're CalcultingRocketFlightProfile class needs parameters, but you're creating calculations without passing any parameters to the new CalcultingRocketFlightProfile.
You should store those inputs in variables, then pass those variables to the constructor in your new CalcultingRocketFlightProfile that you declare.
Well, first off you are not actually passing any of your input to the Calculations class. I am not sure what input.input1() is or if you have an input class that you did not post. Either way you can do this a couple different ways.
First off give your input variables a meaningful name so you know which ones you are dealing with. Then pass all of your input.
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile(input1, input2, etc..)
or
Place all your input variables into your calculations class. Then store user input as calculations.totalImpulse, etc... Then you call your calculation methods to display answers.
-EDIT-
Just have 2 classes, your main and calculations class. There is no need for another class just to handle keyboard input.
Example
Main class
public class Main {
public static void main( String args[] ) {
Scanner keyboard = new Scanner(System.in);
CalculatingRocketFlightProfile calculations = new CalculatingRocketFlightProfile();
System.out.print("\nPlease enter a number for Total Impulse: " );
calculations.totalImpulse = keyboard.nextDouble();
System.out.println("You have entered : " + calculations.totalImpulse);
}
}
public class CalculatingRocketFlightProfile { //Calculation class
//Declaring fields
public double totalImpulse ;
// Do all of your maths, and methods for answer return
}
You were not actually taking the keyboard input and assigning it to anything. Using a scanner object you can assign the input to a variable in your calculations class. If you do that for all of them, you dont actually need a constructor in your calculations class, you just use it to do all that math and return answers.

Java: Returning Multiple Values to Main Method In Order To Compute Total

The code is below. The program runs a series of calculations based on data input by the user. My problem is that for the most important thing I'm looking for, total kg CO2 emissions, I continually get an answer of 0.0. What I need is a sum of the individual total emissions as calculated in each method, i.e. the values which are printed with the following: System.out.println(trans); System.out.println(elec); and System.out.println(food);
The total should be something like 25040 or whatever, depending on the value of the inputs provided by the user, but I'm constantly getting a total of 0.0., which is obviously false. Could have something to do with the way I've initialized my variables, or something to do with the limitations of returning values from methods. I just don't know what to do. How should I tackle this? All help greatly appreciated!
import java.util.Scanner;
public class CarbonCalc {
public static void main(String[] args) {
double trans = 0;
double elec = 0;
double food = 0;
giveIntro();
determineTransportationEmission(null);
determineElecticityEmission(null);
determineFoodEmission(null);
calculateTotalEmission(trans, elec, food);
//printReport(trans, elec, food);
}
//Gives a brief introduction to the user.
public static void giveIntro() {
System.out.println("This program will estimate your carbon footprint");
System.out.println("(in metric tons per year) by asking you");
System.out.println("to input relevant household data.");
System.out.println("");
}
//Determines the user's transportation-related carbon emissions.
public static double determineTransportationEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will first begin with your transportation-related carbon expenditures...");
System.out.print("How many kilometres do you drive per day? ");
double kmPerDay = console.nextDouble();
System.out.print("What is your car's fuel efficiency (in km/litre)? ");
double fuelEfficiency = console.nextDouble();
System.out.println("We now know that the numeber of litres you use per year is...");
double litresUsedPerYear = 365.00 * (kmPerDay / fuelEfficiency);
System.out.println(litresUsedPerYear);
System.out.println("...and the kg of transportation-related CO2 you emit must be...");
//Final calculation of transportation-related kgCO2 emissions.
double trans = 2.3 * litresUsedPerYear;
System.out.println(trans);
System.out.println("");
return trans;
}
//Determines the user's electricity-related carbon emissions.
public static double determineElecticityEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your electricity-related carbon expenditures...");
System.out.print("What is your monthly kilowatt usage (kWh/mo)? ");
double kWhPerMonth = console.nextDouble();
System.out.print("How many people live in your home? ");
double numPeopleInHome = console.nextDouble();
System.out.println("The kg of electricity-related CO2 you emit must be...");
//Final calculation of electricity-related kgCO2 emissions.
double elec = (kWhPerMonth * 12 * 0.257) / numPeopleInHome;
System.out.println(elec);
System.out.println("");
return elec;
}
//Determines the user's food-related carbon emissions.
public static double determineFoodEmission(Scanner input) {
Scanner console = new Scanner(System.in);
System.out.println("We will now move on to your food-related carbon expenditures...");
System.out.print("In a given year, what percentage of your diet is meat? ");
double meat = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is dairy? ");
double dairy = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is fruits and veggies? ");
double fruitVeg = console.nextDouble();
System.out.print("In a given year, what percentage of your diet is carbohydrates? ");
double carbs = console.nextDouble();
//Final calculation of food-related kgCO2 emissions.
System.out.println("The kg of food-related CO2 you emit must be...");
double food = (meat * 53.1 + dairy * 13.8 + fruitVeg * 7.6 + carbs * 3.1);
System.out.println(food);
System.out.println("");
return food;
}
//Calculates total emissions across all sources.
public static double calculateTotalEmission(double trans, double elec, double food) {
System.out.println("Your total kg of CO2 emitted across all sources is equal to...");
double total = trans + elec + food;
System.out.println((double) total);
System.out.println("");
return total;
}
}
Ah!! Thank you very much Lyju. I did the following and it all worked well.
From this:
double trans = 0;
double elec = 0;
double food = 0;
To this:
double trans = determineTransportationEmission(null);
double elec = determineElecticityEmission(null);
double food = determineFoodEmission(null);
The second problem which popped up here had to do with not correctly passing the Scanner parameter to the multiple methods.
I fixed that by adding the following to the main method:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
double trans = determineTransportationEmission(console);
double elec = determineElecticityEmission(console);
double food = determineFoodEmission(console);
giveIntro();
calculateTotalEmission(trans, elec, food);
}
And because I had three scanner objects, one for each method, I simply removed the Scanners in each and can now pass a single Scanner from my main method to each of the others.

Categories

Resources