How to write a mathematical formula in Java - java

I'm trying to figure out a way of converting kilograms (entered by user) to stone and pounds.
For example:
User enters weight as 83.456 kgs, multiply this by 2.204622 to convert to pounds = 184 lbs, divide 184 lbs by 14 to convert to stone = 13.142 stone.
Use the first two digits (13) for stone and separate the remainder to multiply by 14 to get pounds, 0.142 (this is remainder) x 14 = 1.988 lbs, or is there another way to get this result?
Therefore the persons weight is 13 stone and 2 pounds (rounded up or down).
Here's what I have (that works) so far:
pounds = kgs*2.204622;
System.out.printf("Your weight in pounds is: %.0f" , pounds);
System.out.print(" Ibs\n");
stone = pounds / 14
//Can't figure out how to finish the formula in code

I'm assuming that you declared pounds and stone before using them here (i.e. with float pounds; or double pounds; or float pounds = something), or the code wouldn't compile otherwise.
One way to do this is to do it in 2 separate steps, as below:
double kg = 83.456;
double pounds = kg * 2.204622;
double stonesWithDecimal = pounds / 14;
int stone = (int) stonesWithDecimal; // Strip off the decimal
long poundsWithoutStone = Math.round((stonesWithDecimal - stone) * 14); // Take the fractional remainder and multiply by 14
System.out.println("Stone: " + stone + "\nPounds: " + poundsWithoutStone);
Andreas's suggestion is definitely much cleaner, though I wanted to present both since I'm not sure what your familiarity level is with using modulo in programming.
Here's one implementation of that suggestion, though you can do this a few different ways in terms of dealing with the data types (Math.round wants to return a long):
double kg = 83.456;
double pounds = kg * 2.204622;
int stone = (int) pounds / 14;
pounds = (double) Math.round(pounds %= 14);
System.out.println("Stone: " + stone + "\nPounds: " + pounds);

If you are looking for an extensible ready to use library, you can consider Free & open-sourced library UnitOf
It offers 30+ conversion out of the box for Mass.
Example :
double kgFromPound = new UnitOf.Mass().fromPounds(5).toKilograms();
double poundFromKg = new UnitOf.Mass().fromKilograms(5).toPounds();
Hope it helps!

The correct solution rounds early. Here is code as suggested by my initial comment:
double kgs = 83.456;
long pounds = Math.round(kgs*2.204622);
System.out.println("Your weight is " + pounds / 14 + " stone and " + pounds % 14 + " pounds");
Output
Your weight is 13 stone and 2 pounds
If you instead use 69.853 kgs, you get
Your weight is 11 stone and 0 pounds
but this is where thing get dicey if you don't round early.
Both solutions in the (currently accepted) answer by Lightning are wrong, since they round at the wrong time. There is a reason you have to round early.
If you change to use 69.853 kgs in those two solutions, you get
Solution 1:
Stone: 10
Pounds: 14
Solution 2:
Stone: 10
Pounds: 14.0
Both are obviously incorrect, since Pounds should not be 14, aka 1 stone.
The reason for the rounding errors becomes evident if you print the values without rounding
double kgs = 69.853;
double pounds = kgs*2.204622;
System.out.println(pounds + " lbs = " + pounds / 14 + " stone and " + pounds % 14 + " pounds");
Output
153.99946056599998 lbs = 10.999961468999999 stone and 13.999460565999982 pounds

Related

Java - How to Validate Numerical User Input Within A Certain Range Correctly

Just looking for a little help! I am working on a weight conversion program at the moment. I have it working correctly but now I'm trying to make it fool proof, i.e. if a user inputs a numerical value either below or over a certain range (in this case I'm looking for KG between the range of 0 and 450) a message will appear advising of the mistake and will then prompt the user to input their value again. I can do that with the following code but the problem is when the user inputs a valid value it will print the conversion of not only the valid input but also the previous incorrect value. I have attached a screenshot of Command Prompt demonstrationg the issue. Can someone please tell me where I'm going wrong? Thanks.
public void kgToStonesAndPounds()
{
double kg = 0;
System.out.println("Please enter weight in KG here, range must be between 1 and 450: ");
kg = input.nextDouble();
if ( kg >= 1 && kg <= 450 ) // validate kg
System.out.printf("\nThe weight you have entered is %.0f KG\n" , kg);
else
{System.out.println( "Weight in KG must be in the range of 1 - 450" );
this.kgToStonesAndPounds();
}
double pounds = kg * 2.204622;
double stonesWithDecimal = pounds / 14;
int stone = (int) stonesWithDecimal; // cast int to get rid of the decimal
long poundsWithoutStone = (long)((stonesWithDecimal - stone) * 14); // Take the fractional remainder and multiply by 14
System.out.println("This converts to " + stone + " Stone " + poundsWithoutStone + " Pounds " );
}//end method kgToStonesAndPounds
EXAMPLE IN COMMAND PROMPT
You have to add a return after you call the method again in the invalid case. That way when returning from the method call if it was called from this method it won't move out of else statement and execute the following code.
public void kgToStonesAndPounds() {
...
if ( kg >= 1 && kg <= 450 ) // validate kg
System.out.printf("\nThe weight you have entered is %.0f KG\n" , kg);
else {
System.out.println( "Weight in KG must be in the range of 1 - 450");
this.kgToStonesAndPounds();
return; // here
}
...
}
Java - How to Validate Numerical User Input Within A Certain Range Correctly
As long as you get the desired effect/result (sans bad side effects), one way is no more correct than another.
Here is how I might do it. Just prompt initially and then repeat the prompt if the input isn't correct.
double kg;
String prompt = "Please enter weight in KG here, range must be between 1 and 450: ";
System.out.println(prompt);
while ((kg = input.nextDouble()) < 1 || kg > 450) {
System.out.println(prompt);
}
System.out.printf("\nThe weight you have entered is %.0f KG\n" , kg);
// now do something with kg
Recursion (call a method inside itself) isn't a way to handle errors, it should only be used when the logic requires it.
To ask again, use a loop that will exits only when the input is valid
double kg;
do {
System.out.println("Please enter weight in KG here, range must be between 1 and 450: ");
kg = input.nextDouble();
if (kg >= 1 && kg <= 450) {
System.out.printf("\nThe weight you have entered is %.0f KG\n", kg);
break;
} else {
System.out.println("Weight in KG must be in the range of 1 - 450");
}
} while (true);
And you can use modulo to simplify your code
double pounds = kg * 2.204622;
int stone = (int) pounds / 14;
int poundsWithoutStone = (int) pounds % 14;
System.out.println("This converts to " + stone + " Stone " + poundsWithoutStone + " Pounds ");
Both Ausgefuchster and azro' answer work, I give my answer as additional one for discuss.
I think most of your code works fine, but you should struct your code more clearly. For the if statement and else statement has no common code to execute, thus all code in the method should be seperate into different branches. Like the following:
public void kgToStonesAndPounds()
{
double kg = 0;
System.out.println("Please enter weight in KG here, range must be between 1 and 450: ");
kg = input.nextDouble();
if ( kg >= 1 && kg <= 450 ){ // validate kg
System.out.printf("\nThe weight you have entered is %.0f KG\n" , kg);
double pounds = kg * 2.204622;
double stonesWithDecimal = pounds / 14;
int stone = (int) stonesWithDecimal; // cast int to get rid of the decimal
long poundsWithoutStone = (long)((stonesWithDecimal - stone) * 14); // Take the fractional remainder and multiply by 14
System.out.println("This converts to " + stone + " Stone " + poundsWithoutStone + " Pounds " );
}
else
{System.out.println( "Weight in KG must be in the range of 1 - 450" );
this.kgToStonesAndPounds();
}
}//end method kgToStonesAndPounds
The reason that led to this problem is that after recursive execution of kgToStonesAndPounds completes, the code will continue to run the rest codes which follow the else block.

HomeWork: Convert Feet to Inches with RNG

"Write a program that will randomly generate a number of total inches. Then convert the total inches into feet and inches."
I need to make the output in this format:
14 inches is 1 feet, and 2 inches
I already have this starting code:
public class InchesToFeet {
public static void main(String[] args) {
convert(); // convert feet to inches and output
}
// This method generate a random number of total inches.
// It then converts to feet and inches and outputs the answer.
public static void convert() {
// randomly picks a number between 1-200
int totalInches = (int)(Math.random()*200 + 1);
// Convert to feet and inches.
// ex. if totalInches is 38, the output would be: 38 inches is 3 feet, and 2 inches
// ADD CODE BELOW
}
}
I read the chapter that our professor assigned but I am honestly lost on as to how to actually do this. Thanks!
To achieve your aim, you need to first divide totalInches by your conversion factor (12) to see how many feet it contains, and then use the modulo operator (%) to get the number of inches - like so.
System.out.println(totalInches + " inches is " + (int) (totalInches / 12) + " feet, and " + totalInches % 12 + " inches");
Still, pasting homework on here isn't such a good idea.

Splitting units base of a number and separating remainders

I am trying to split a number of a base then separating the two numbers to get different outputs. (Keep in mind I just edited, my answer is the solution). This is left here so people that have a similar problem can find a solution. Thank you all!
So this is the idea:
If number >= 10 && of base 10
Then give me discounted price on 10 units
if number <= 0 && not base 10
Then add the discount for the number which has 10 units in it and the remainder without the discount (let's say 100% for simplicity sake of the numbers)
So to make a practical example
If I order 25 units of x (at $1 each) and 15 units (at $1 each) of y the price will be:
x 20 units = $0
x 5 units = $5 total
y 10 units = $0
y 5 units = $5 total
This is a bit tricky and this is what I got so far:
double discountedmNI = (mNI - ((mNI/100)*10)) * mNIC;
double discountedmNIP = mNI - ((mNI/100)*10);
if(mNIC >= 10 && mNIC % 10 == 0){
System.out.println("mNI " + discountedmNIP + " " + mNIC);
System.out.println(discountedmNI);
}
else if (!mNIC % 10 == 0){
System.out.println("mNI " + mNI + mNIC);
System.out.println(mNI * mNIC);
}
I don't think I am defining separate the 10 units right
Thank you all!
I hope I understood you right. I get that you want to calculate a total price that consists of two elements: the price for non-discounted items and a price for discounted items.
// The following three values are just example assumptions.
float discountInPercent = 100.0f;
float itemsOrdered = 5004.0f;
float itemPriceNormal = 5.0f;
// Here the price for one discounted item gets calculated.
// Please remember that the discount is given in percentage.
float itemPriceDiscounted = itemPriceNormal * ((100.0f - discountInPercent) / 100.0f);
// Calculate the count of items that get discounted and those that
// will get priced normally.
float itemsDiscounted = Math.floor(itemsOrdered / 10.0f);
float itemsNotDiscounted = itemsOrdered % 10;
// Finally calculate the two elements of the total price and sum it up.
float priceDiscounted = (itemsDiscounted * itemPriceDiscounted);
float priceNormal = (itemsNotDiscounted * itemPriceNormal);
float totalPrice = priceDiscounted + priceNormal;
System.out.println("Price discounted: %.2f" + priceDiscounted);
System.out.println("Price non-discounted: %.2f" + priceNormal);
System.out.println("Price total: %.2f" + totalPrice);
EUREKA!
double discountedmNIP = mNI - ((mNI/100)*10);
int mNIC2 = (mNIC % 10);
double mNIC2disc = (mNI * mNIC2);
double discountedmNI = (mNI - ((mNI/100)*10)) * (mNIC - mNIC2);
if(mNIC >= 10){
System.out.println(discountedmNIP + " " + (mNIC - mNIC2) + " " + discountedmNI );
System.out.println(mNI + " " + mNIC2 + " " + mNIC2disc);
}
else{
System.out.print(mNI + " " + mNIC);
System.out.print(mNI * mNIC);
}
double sum = (mNI + discountedmNI + discountedRh + rH);
System.out.println('\t');
System.out.println("Total order cost " + sum);
All I need to do is to take the units % 10 which will divide the left side integer or double by the right side (left side input from user)
and will give me the remainder when I do that variable subtracted to the original variable!
Again, this small step took me a whole night to figure it out, and is simple indeed. This is for a class, and if you are in that class and you are reading (even though you might have to dig a little to find what assignment is this one), I would just like to tell you this is what's fun about programming! I am not being sarcastic I really love these type of problems!
Signed:
That foreign guy;
EUREKA again!
Enjoy!

Dynamically calculating change to the nearest 10 dollars

I am new to Java and I'm trying to figure out how to dynamically calculate the change to the nearest 10 dollars. For instance, the user inputs a value (34.36), my code then calculates tip, tax, and total amount for the bill (total 44.24). Without user input, I need to calculate the change from $50.00. I've tried to round up to 50.00 from 44.24 with no luck, obviously I am doing something wrong. I've tried Math.round and tried to find the remainder using %. Any help on how to get the total change due to the nearest 10 dollar value would be great. Thank you in advance, below is my code:
Full dis-closer, this is a homework project.
import java.util.Scanner;
import java.text.NumberFormat;
import java.lang.Math.*;
public class test1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
//Get input from user
System.out.println("Enter Bill Value: ");
double x = sc.nextDouble();
//Calculate the total bill
double salesTax = .0875;
double tipPercent = .2;
double taxTotal = (x * salesTax);
double tipTotal = (x * tipPercent);
double totalWithTax = (x + taxTotal);
double totalWithTaxAndTip = (x + taxTotal + tipTotal);
//TODO: Test Case 34.36...returns amount due to lower 10 number
//This is where I am getting stuck
double totalChange = (totalWithTaxAndTip % 10);
//Format and display the results
NumberFormat currency = NumberFormat.getCurrencyInstance();
NumberFormat percent = NumberFormat.getPercentInstance();
//Build Message / screen output
String message =
"Bill Value: " + currency.format(x) + "\n" +
"Tax Total: " + currency.format(taxTotal) + "\n" +
"Total with Tax: " + currency.format(totalWithTax) + "\n" +
"20 Percent Tip: " + currency.format(tipTotal) + "\n" +
"Total with Tax and 20 Percent Tip: " + currency.format(totalWithTaxAndTip) + "\n" +
"Total Change: " + currency.format(totalChange) + "\n";
System.out.println(message);
}
}
you make
double totalChange = round((totalWithTaxAndTip / 10)) * 10;
Math.round rounds a number to the nearest whole number, so as others have shown, you need to divide by 10, then multiply by 10 after rounding:
double totalChange = tenderedAmount - totalWithTaxAndTip;
double totalChangeRounded = 10 * Math.round(totalChange / 10);
Math.ceil(double) will round up a number. So what you need is something like that:
double totalChange = (int) Math.ceil(totalWithTaxAndTip / 10) * 10;
For totalWithTaxAndTip = 44.24, totalChange = 50.00
For totalWithTaxAndTip = 40.00, totalChange = 40.00
Everyone, thank you very much for helping me. I tested out everyone's solution. This is my final working code.....
double totalAmountPaid = totalWithTaxAndTip - (totalWithTaxAndTip % 10) + 10;
I tested it out using many different values and it seems to be working the way I want it to.
Again, I appreciate everyone for taking the time to help me out.

Kilograms to Pounds and Ounces

I'm trying to write a program that converts kilograms to pounds and ounces. If the user enters 100 kilograms the result I'm expecting is 220 pounds and 7.4 ounces.
I get the correct pound value but my problem is getting the correct ounces value. I don't know what I'm missing. Also when I calculate the ounces value, how do i specify to the program that I only want the answer to the hundredth degree. For example I only want 7.4 ounces and not 7.4353?
import acm.program.*;
public class KilogramsToPoundsAndOunces extends ConsoleProgram {
public void run() {
println("This program converts Kilograms into Pounds and Ounces.");
int kilo = readInt("please enter a number in kilograms: ");
double lbs = kilo * POUNDS_PER_KILOGRAM;
double oz = lbs * OUNCES_PER_POUND;
double endPounds = (int) oz / OUNCES_PER_POUND;
double endOunces = oz - (endPounds * OUNCES_PER_POUND);
println( endPounds + " lbs " + endOunces + "ozs");
}
private static final double POUNDS_PER_KILOGRAM = 2.2;
private static final int OUNCES_PER_POUND = 16;
}
The easiest way would be to use System.out.printf and format the output there:
System.out.printf("%d lbs %.1f ozs", endPounds, endOunces);
If you can't use System.out.printf, you can still use String#format to format the output:
println(String.format("%d lbs %.1f ozs", endPounds, endOunces));
Cases where you need exact decimal value; its better to use BigDecimal data type instead of double.
The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. link
BigDecimal provides methods to round the number to given value.
Use DecimalFormat to print the decimal places in desired format e.g.
DecimalFormat dFormat = new DecimalFormat("#.0");
System.out.println( endPounds + " lbs " + dFormat.format(endOunces) + " ozs");
If you want rounding done upto one decimal place, then multiply the number by 10, round, then divide again and print as below:
double roundedOunces = Math.round(endOunces*10)/10.0;
DecimalFormat dFormat = new DecimalFormat("#.0");
System.out.println( endPounds + " lbs " + dFormat.format(roundedOunces) + " ozs");
EDIT:
Try this for rounding:
double roundedOunces = Math.round(endOunces*10)/10.0;.
Without rounding:
double roundedOunces = endOunces*10/10.0;

Categories