The first part of the code is working, the program takes inputs as height and weight as displays an output message. When I press n I can go to the second part and take inputs for height in inches and the weight in pounds. As soon as I take them the program outputs the resulting bmi is: Nan. and the variable bmi might not have been initialized. i want to convert the height and weight from inches and pounds to meters and then show the resulting bmi This is my code:
package uly14th;
import java.util.Scanner;
public class BmiCalculator {
private static float BMI2;
public static void main(String[] args) {
char Y;
char y;
char Q;
char n;
char N;
float heightInMeters, weightInKilograms, BMI;
float heightInInches, weightInpounds;
float heightInMeters2 = 0, weightInKilograms2 = 0;
Scanner input = new Scanner(System.in);
System.out.println("Please state whether you are going to use kilograms & meters or, inches & pounds");
System.out.println("If you want to use the former please press Y or if you want to use the latter please press N");
Q = input.next().charAt(0);
if(Q == 'y' || Q == 'Y' ) {
System.out.println("Please enter the height in meters: ");
heightInMeters = input.nextFloat();
System.out.println(" and weight in kilograms: ");
weightInKilograms = input.nextFloat();
BMI = weightInKilograms / (heightInMeters * heightInMeters);
System.out.println("The resulting BMI of the person is: " +BMI);
if (BMI < 18.5){
System.out.println("The personis underweight");
}
else if ((BMI<=25.0) && (BMI >= 18.5)){
System.out.println("The person is normal");
}
else if ((BMI >= 25.0) && (BMI <=30.0 )){
System.out.println("The personis obese");
}
else if(BMI>=30.0) {
System.out.println("The person is obese and should exercise");
}
}
if ((Q == 'n') || (Q == 'N')){
System.out.println("Please enter the height in inches: ");
heightInInches = input.nextFloat();
System.out.println("Please enter the weight in pounds: ");
weightInpounds = input.nextFloat();
heightInInches = 0.0254f * heightInMeters2;
weightInpounds = 0.453592f * weightInKilograms2;
BMI = weightInKilograms / (heightInMeters * heightInMeters);
System.out.println("The resulting BMI of the person is: " +BMI);
if (BMI < 18.5){
System.out.println("The personis underweight");
}
else if ((BMI<=25.0) && (BMI >= 18.5)){
System.out.println("The person is normal");
}
else if ((BMI >= 25.0) && (BMI <=30.0 )){
System.out.println("The personis obese");
}
else if(BMI>=30.0) {
System.out.println("The person is obese and should exercise");
}
}
else {
System.out.println("Please make sure you run the program again and then only use the characters n,N,y,Y. ");
}
}
}
This is the error message: Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - variable BMI might not have been initialized
at uly14th.BmiCalculator.main(BmiCalculator.java:82)
At the row (line 82)
BMI = weightInKilograms / (heightInMeters * heightInMeters);
you use the variables weightInKilograms and heightInMeters which has never been initialized, hence your error.
I suspect you want to do the conversion to meters and kilograms from inches and pounds before calculating the BMI. You can do this by simply putting the following lines before the BMI calculation
heightInMeters = 0.0254f * heightInInches;
weightInKilograms = 0.453592f * weightInPounds;
BMI = weightInKilograms / (heightInMeters * heightInMeters); //Now you can calculate the BMI using your variables since they have been assigned a value and is therefore initialized
heightInMeters = 0.0254f * heightInInches ;
weightInKilograms = 0.453592f * weightInpounds ;
BMI = weightInKilograms / (heightInMeters * heightInMeters);
should do the trick (... in case the constants are correct)
Related
I'm writing a program that will calculate the BMI of a person. Here's the assignment that I was given:
"Body Mass Index (BMI) is a measure of health on weight. It can be calculated by taking your weight in kilograms and dividing by the square of your height in meters. Write a program that prompts the user to enter a weight W in pounds and height H in inches and displays the BMI. Note that one pound is 0.45359237 kilograms and one inch is 0.0254 meters."
Input: (Line 1) Real number within 50 to 200
(Line 2) Real number within 10 to 100
Output: BMI value (Floating point should only be printed until the second decimal point)
The problem is that whenever I use "System.out.printf("%.2f\n", BMI)", the output is rounded up rather than cutting off the rest of the decimal point. Here's my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
double weight = input.nextDouble();
double height = input.nextDouble();
double weightKG;
double heightM;
double heightMSquare;
double BMI;
final double kilogram = 0.45359237;
final double meter = 0.0254;
while ((weight > 200) || (weight < 50)) // Error catching code.
{
weight = input.nextDouble();
}
while ((height > 100) || (height < 10))
{
height = input.nextDouble();
}
weightKG = weight * kilogram; // Convert pounds and inches to
kilograms and meters.
heightM = height * meter;
heightMSquare = Math.pow(heightM, 2); // Compute square of height in
meters.
BMI = weightKG / heightMSquare; // Calculate BMI by dividing weight
by height.
System.out.printf("%.2f\n", BMI);
}
}
Here is a method I wrote that solves this with regexes and string manipulation.
private static String format2Dp(double x) {
String d = Double.toString(x);
Matcher m = Pattern.compile("\\.(\\d+)").matcher(d);
if (!m.find()) {
return d;
}
String decimalPart = m.group(1);
if (decimalPart.length() == 1) {
return d.replaceAll("\\.(\\d+)", "." + decimalPart + "0");
}
return d.replaceAll("\\.(\\d+)", "." + decimalPart.substring(0, 2));
}
What I did was turning the double to a string, extract the decimal part out of it and substringing the decimal part. If the decimal part is only 1 character long, add a zero to the end.
This method works with numbers expressed in scientific notation as well.
The question says The Fast Freight Shipping Company charges the following rates:
Weight of Package Rate per 500 Miles Shipped
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80
The shipping charge per 500 miles are not prorated. For example, if a 2-pound package is shipped 550 miles, the charges would be $2.20. Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
My problem is that I keep receiving two different answers everytime I put in a weight and distance. For example when I enter the weight as 2 pounds and the distance as 500 miles I get the answers $0.0 and $3.8 which are both incorrect answers. It looks like some weights that I enter are correct answers and others I enter give me incorrect answers. Heres my program:
//import java utilities for scanner class
import java.util.Scanner;
public class ShippingCharge
{
public static void main (String[] args)
{
//Declare and initialize variable to hold the entered weight.
int weight = 0;
//Declare and initialize variable to hold the entered distance.
double distance = 0.0;
//This variable will hold the calculated rate.
double rate;
//This will decide if the shipping charge will advance up one level.
int distanceMultiplier = (int)distance / 500;
//This will hold the increments of the shipping charge.
int distanceRemainder;
//Create a Scanner object for the input.
Scanner input = new Scanner(System.in);
//Get the weight of the package.
System.out.println("What is the weight of the package (in pounds)?");
weight = input.nextInt();
//Get the shipping distance of the package.
System.out.println("What is the shipping distance (in miles)?");
distance = input.nextDouble();
distanceRemainder = (int)distance % 500;
if (distanceRemainder == 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.70));
}
else
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.80));
}
if (distanceRemainder != 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.70);
}
else
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.80);
}
//end program
System.exit(0);
}//end main
}//end class
This will work for you
public static void main(String[] args) {
int weight = 0;
double distance = 0.0 , distanceExtra ;
Scanner in = new Scanner(System.in);
System.out.println("Weight ? ");
weight = in.nextInt();
System.out.println("Distance ? ");
distance = in.nextDouble();
distanceExtra = distance / 500;
distanceExtra = Math.ceil(distanceExtra);
if (weight <= 2) {
System.out.printf("charge is :" , (distanceExtra * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.printf("charge is :" , (distanceExtra * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.printf("charge is :" , (distanceExtra * 3.70));
}
else if (weight > 10)
{
System.out.printf("charge is :" , (distanceExtra * 4.80));
}
}
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
int weight = 0;
double distance = 0.0 ;
Scanner keyboard =new Scanner(System.in);
System.out.println("Enter the Distance");
distance = keyboard.nextDouble();
System.out.println("Enter the Weight");
weight = keyboard.nextInt();
if (weight <= 2) {
System.out.println("charge is : " + "$"+1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("charge is : " + "$"+2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("charge is : " + "$"+3.70);
}
else if (weight > 10)
{
System.out.println("charge is :" + "$"+4.80);
}
}
}
I am getting a NaN error when I compile this, i can't figure out what I am doing wrong? I tried moving the variables around to see if I could get them working but nothing. Notice the variable I put of type double i used for bmi after inches = keyboard.nextInt(); I think its a divide by zero error but i dont know what i am dividing by zero.
import java.util.Scanner;
public class BodyMassIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
int pounds =0;
int feet = 0;
int inches = 0;
double heightMeters = ((feet * 12) + inches) * .0254;
double mass = pounds / 2.2;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your weight in pounds");
pounds = keyboard.nextInt();
System.out.println("Enter how many feet you are");
feet = keyboard.nextInt();
System.out.println("Enter how many inches after feet");
inches = keyboard.nextInt();
double bmi = mass / (heightMeters * heightMeters);
System.out.println(mass);
System.out.println(bmi);
if(bmi < 18.5){
System.out.println("Underweight");
}
else if ((bmi >= 18.5) && (bmi < 25)){
System.out.println("Normal weight");
}
else if ((bmi >= 25) && (bmi < 30))
System.out.println("Above weight");
else
System.out.println("Obese");
}
}
It's important to understand the dynamic nature of your variables, such that when you type
double heightMeters = ((feet * 12) + inches) * .0254;
This assignment is immediately evaluated using the current values of feet and inches (which are 0 at that moment), before any of the keyboard entry is performed. To perform these calculations with the values entered by the keyboard, these calculations need to be performed and their results assigned to their corresponding variables after the keyboard entry is done, when the current values of pounds, feet and inches are what you just entered. Because heightMeters is still zero from its initialization and hasn't been changed since, you're getting a divide by zero.
You're getting the exception because the value of heightMeters is 0 here:
double bmi = mass / (heightMeters * heightMeters);
The only time that heightMeters is calculated, the result of it is 0:
double heightMeters = ((feet * 12) + inches) * .0254;
It looks like you want to use this calculation, so I'd split it into a separate function:
public static double getHeightInMeters(int feet, int inches)
{
return 0.0254 * ((feet * 12) + inches);
}
Then you can call it later:
double heightMeters = this.getHeightInMeters(feet, inches);
double bmi = mass / (heightMeters * heightMeters);
It may be rather simple but I am having issues returning a value for "circum" here is my code.
double circRad = 0;
double circum = 0;
if(userOption == 2){
circRad = myRad();
System.out.println("The Radius of the circle is " + circRad + " and it perimeter is "+ circum);
public static double myRad(){
int i= 1;
double circRad = 0;
Scanner myInput=new Scanner(System.in);
switch(i)
{
case 1:
System.out.print("Please enter a positive Radius for the circle ");
circRad = myInput.nextDouble();
while(circRad <0){
System.out.print("Please enter a POSITIVE Radius for the circle ");
circRad = myInput.nextDouble();
}
++i;
}
return circRad;
}
public static double myRad(double circRad){
double circum = 0;
circum = 2* Math.PI * circRad;
return circum;
}
Perhaps you are missing the following:
if(userOption == 2){
circRad = myRad();
circum = myRad(circRad); // <-- missing setting local circum value
System.out.println("The Radius of the circle is " + circRad + " and it perimeter is "+ circum);
}
Only thing I could guess about the code with the way it is presented is that circRad and circum are global variables, therefore when you call the first myRad() only circRad changes. However, circum remains 0.
If you could sent the entire code, it'll make everything easier.
My code compiles correctly. When I run my program the output asks me to enter weight of package. If I enter a negative number the program asks me to enter weight again, but won't stop to let me enter another number.
I think the problem is in the "while" statement but I'm not sure.
Any help would be appreciated.
import java.util.Scanner;
public class dcrawford_Shipping
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int weight, distance, distancex;
double rate, price;
rate = 0.00;
System.out.print("Please enter package weight: ");
weight = input.nextInt();
while (weight <= 0 || weight >= 61)
{
System.out.print("Please enter package weight: ");
}
if (weight <= 10 && weight >= 1 )
{
rate = 5.01;
}
else if ( weight <= 20 && weight >= 11 )
{
rate = 7.02;
}
else if ( weight <= 30 && weight >= 21 )
{
rate = 9.03;
}
else if ( weight <= 40 && weight >= 31 )
{
rate = 11.04;
}
else if ( weight <= 60 && weight >= 41)
{
rate = 15.00;
}
System.out.print("Please enter distance: ");
distance = input.nextInt();
while ( distance <= 0 )
{
System.out.print("Please enter distance: ");
}
distancex = ( distance / 100 ) + 1;
price = ( distancex * rate );
System.out.printf("Your total shipping cost for %d miles is $%.2f\n", distance, price);
}
}
You need to ask the user to enter the weight again inside of the while loop.
while (weight <= 0 || weight >= 61) {
System.out.print("Please enter package weight: ");
weight = input.nextInt();
}
You could also use a do-while loop:
do {
System.out.print("Please enter package weight: ");
weight = input.nextInt();
} while (weight <= 0 || weight >= 61);
If you use the do-while loop, you can remove the first time you ask and the while loop. It's a slightly more compact way of doing it.