HomeWork: Convert Feet to Inches with RNG - java

"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.

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.

Converting feet and inches to inches (multiple inputs into one input)

This program has me stumped. I'm trying to figure out a way to convert input from this:
System.out.print("Enter your height in inches (e.g. 57): ");
String height = in.nextLine();
height += in.nextLine();
System.out.println();
and turn it into just inches. How do I separate the feet from the inches, change said feet to inches and combine them into a sum of inches once again?
System.out.print("Enter your height in inches (e.g. 57): ");
int heightInInches = in.nextInt();
int heightInFeet = heightInInches / 12;
int heightInchesRemaining = heightInInches % 12;
System.out.println(heightInFeet + "\' " + heightInchesRemaining + "\"");
You can convert into ft. and in. format by doing that. Then do whatever you need to with the rest of the operations that you described.
first of all, your question and sample code is confusing so I will base my answer on your last statement. From my understanding, you ask the user to input his height in feet first then the remaining inches and convert this info to inches only (e.g 5'7 to 67 inches)
System.out.print("Enter your height in feet. (e.g, 5 if your height is 5'7) : ");
int height = in.nextInt() * 12;
System.out.print("Enter your height in inches (e.g, 7 if your height is 5'7) : ");
height += in.nextInt();
System.out.println(height);

How to write a mathematical formula in 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

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;

Predicting the number of digits of a multiplication

I need to find the number of digits of very large multiplications (about 300 digits each). I was wondering if there is a trick to predict the number of digits that the product will be without actually performing the calculation.
The number of digits can be calculated exactly by the rounded (down) sum of the base 10 log of the two multiplicands plus 1, as follows:
public static void main(String[] args) {
DecimalFormat f = new DecimalFormat("#");
double num1 = 12345678901234567890d;
double num2 = 314159265358979d;
// Here's the line that does the work:
int numberOfDigits = (int) (Math.log10(num1) + Math.log10(num2)) + 1;
System.out.println(f.format(num1) + " * " + f.format(num2) + " = " +
f.format((num1 * num2)) + ", which has " + numberOfDigits + " digits");
}
Output:
12345678901234567000 * 314159265358979 = 3878509413969699000000000000000000, which has 34 digits
This will work for arbitrarily large numbers.
Cristobalito's answer pretty much gets it. Let me make the "about" more precise:
Suppose the first number has n digits, and the second has m. The lowest they could be is 10^(n-1) and 10^(m-1) respectively. That product would the lowest it could be, and would be 10^(m+n-2), which is m+n-1 digits.
The highest they could be is 10^n - 1 and 10^m - 1 respectively. That product would be the highest it could be, and would be 10^(n+m) - 10^n - 10^m + 1, which has at most m+n digits.
Thus if you are multiplying an n-digit number by an m-digit number, the product will have either m+n-1 or m+n digits.
Similar logic holds for other bases, such as base 2.

Categories