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);
Related
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.
The program lets you input the user's height and weight then outputs the BMI and associated health risk. It converts pounds to kilograms. It also converts the height in feet and inches to meters.
Scanner scanW = new Scanner (System.in);
Scanner scanH = new Scanner (System.in);
System.out.println("Enter your weight in pounds: ");
int weight = scanW.nextInt();
System.out.println("Enter your height in feet followed \nBy a space then additional inches");
String height = scanH.nextLine();
scanW.close();
scanH.close();
int heightFt = height.charAt(0);
int heightInch = height.charAt(2);
int finalHeightFeet = Integer.parseInt(String.valueOf(heightFt));
int finalHeightInch = Integer.parseInt(String.valueOf(heightInch));
double mass = (double) weight / 2.2;
double finalHeight = (double) (finalHeightFeet * 0.3048) + (finalHeightInch * 0.0254);
double BMI = (double) mass / (finalHeight * finalHeight);
System.out.println("Your BMI is " +BMI);
if (BMI < 18.5)
System.out.println("Your risk category is UnderWeight");
else if (BMI < 25)
System.out.println("Your risk category is Normal Weight");
else if (BMI < 30)
System.out.println("Your risk category is Normal Overweight");
else if (BMI >= 30)
System.out.println("Your risk category is Obese");
the correct BMI and risk category output should be:
Your BMI is 25.013498117367398
Your risk category is Overweight.
but my output would be like this:
Your BMI is 0.22261924276759873
Your risk category is UnderWeight
I'm very sure there's a problem in my formula but I can't seem to find it. Would be very helpful if someone pointed out which is wrong
You are not parsing the height input correctly.
Suppose you type
5 9
as the height.
You assign "5 9" to height.
You then parse
int heightFt = height.charAt(0);
int heightInch = height.charAt(2);
which assigns 53 to heightFt and 57 to heightInch (those are the numeric values of the characters '5' and '9').
Try this instead:
String[] height = scanH.nextLine().split (" ");
int heightFt = Integer.parseInt (height[0]);
int heightInch = Integer.parseInt (height[1]);
You are parsing the chars which are represented in numerical values.
Take a look on ASCII TABLE.
For example, if you will put 6 2 as height, the result is actually 54 for 6, 32 for space, and 50 for 2.
scanW.close(); // these two are not necessary
scanH.close();
int heightInch = height.charAt(2); // what if the person is 5' 11" ?
I modified your code a bit, take a look.
Scanner scanW = new Scanner (System.in);
Scanner scanH = new Scanner (System.in);
System.out.println("Enter your weight in pounds: ");
int weight = scanW.nextInt();
System.out.println("Enter your height in feet followed \nBy a space then additional inches");
String height = scanH.nextLine();
int feets = Integer.parseInt(height.substring(0,1));
// get all the chars after index 2
int inches = Integer.parseInt(height.substring(2));
int totalInches = feets * 12 + inches;
double BMI = weight/Math.pow(totalInches, 2) * 703;
System.out.println("BMI: "+BMI);
System.out.println("Enter your weight in pounds: ");
int weight = scan.nextInt();
System.out.println("Enter your height in feet followed \nBy a space then additional inches");
int heightFt = scan.nextInt();
int heightInch = scan.nextInt();
scan.close();
double finalMass = weight / 2.2;
double finalHeight = (heightFt * 0.3048) + (heightInch * 0.0254);
double BMI = finalMass / (finalHeight * finalHeight);
System.out.println("Your BMI is " +BMI);
if (BMI < 18.5)
System.out.println("Your risk category is UnderWeight");
else if (BMI < 25 && BMI >= 18.5)
System.out.println("Your risk category is Normal Weight");
else if (BMI < 30 && BMI >= 25)
System.out.println("Your risk category is Overweight");
else
System.out.println("Your risk category is Obese");
"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.
first question here. I have to use a previous assignment of calculating BMI, and reformat it to accept command line arguments as inputs for height and weight.
"Your program shall obtain the weight and the height via main(String[] args), i.e,, when you run your program you must do the following:
java MyProgramName 180 5 7
where MyProgramName is the name of your program, 180 is the weight in pounds, 5 is the feet and 7 is the inch values.
The program shall output the BMI value in the terminal window as it was before (item f below)."
I am confused on how to call the arguments into the code while performing operands on them.
Here is my original code:
'int weight;
int heightInInches;
int bmi;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your weight in pounds: ");
weight = keyboard.nextInt();
System.out.print("Enter your height in inches: ");
heightInInches = keyboard.nextInt();
bmi = ((weight * 703)/(heightInInches * heightInInches));
System.out.println("Your height is " + heightInInches + " and your
weight is: " + weight + " pounds");
System.out.println("Your BMI is " + bmi);'
I have seen something like this for just adding two numbers, but am confused how to alter it to the BMI formula.
int sum = 0;
for (int i = 0; i < args.length; i++) {
sum = sum + Integer.parseInt(args[i]);
}
System.out.println("The sum of the arguments passed is " + sum);
Thanks
Your String[] args would look something like the s: ["180","5","7"]
So args[0] would be your weight.
args[1] would be the heightInFeet (multiply by 12 to get heightInInches)
args[2] would be the inches part of the height
So the code becomes:
int weight = Integer.parseInt(args[0]);
int heightInInches = Integer.parseInt(args[1])*12 + Integer.parseInt(args[2]);
bmi = ((weight * 703)/(heightInInches * heightInInches));
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 5 years ago.
I am trying to code a basic command line BMI Calculator in Java and for some reason every time I run the code and enter my height and weight, 0 is outputted. Please help me understand where I have made a mistake.
import java.util.Scanner;
public class Chap2 {
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.println("Enter your height in inches: ");
int myHeight = reader.nextInt();
System.out.println("Enter your weight in lbs: ");
int myWeight = reader.nextInt();
int Bmi = (myWeight/myHeight/myHeight)*703;
System.out.println("Your BMI is " + Bmi + ".");
}
}
And my output is as follows:
Enter your height in inches:
68
Enter your weight in lbs:
180
Your BMI is 0.
You are dividing int with int, thus the result is a rounded int.
Cast to double before calculation to get exact results.
double bmi = ((double) myWeight / myHeight / myHeight) * 703;