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));
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");
this is my first post here!
So, as an extra credit project for my Calculus course, the professor offered us an opportunity to write a simple program that calculates the area under a user specified curve. I realize this isn't the best way to implement this, but he say's that's fine, but I think this is giving me the wrong answer. Could anyone help?
import java.util.*;
public class RiemannSum2 {
public static void main(String args []) {
System.out.println("This is a Riemann Sum Calculator. This calculator accepts polynomials in the form of a(x)^ex + b(x)^ex2 + c, where c is a constant.");
System.out.print("Enter the first coeffecient of the polynomial: ");
Scanner sc = new Scanner(System.in);
int firstCoe = sc.nextInt();
System.out.print("Enter the exponent of the first term: ");
int firstExp = sc.nextInt();
System.out.print("Enter the second coeffecient of the polynomial: ");
int secondCoe = sc.nextInt();
System.out.print("Enter the exponent of the second term: ");
int secondExp = sc.nextInt();
System.out.print("Enter the third term of the polynomial: ");
int thirdTerm = sc.nextInt();
System.out.print("Enter the x value that you want to start the Riemann Sum: ");
int startX = sc.nextInt();
System.out.print("Enter the x value to stop the Riemann Sum: ");
int endX = sc.nextInt();
String poly = (firstCoe+"x^"+firstExp+"+"+secondCoe+"x^"+secondExp+"+"+thirdTerm);
System.out.println("Your polynomial is: "+poly);
System.out.print("Enter the number of rectangles you want: ");
int rectangles = sc.nextInt();
double numerator = (endX-startX);
double rectanglesD = (double)rectangles;
double constantWidth = numerator/rectanglesD;
System.out.println("This is the constant width: " + constantWidth);
double totalSum = 0;
//System.out.println(totalSum);
for(int i = 0; i < rectangles ; i++) {
totalSum = totalSum+((Math.pow((firstCoe * (i/constantWidth)), firstExp)) + (Math.pow((secondCoe * (i/constantWidth)), secondExp))+thirdTerm);
}
totalSum = totalSum*constantWidth;
System.out.println("The Riemann Sum of your polynomial is roughly equivalent to: "+ totalSum);
}
}
You use (i/constantWidth) to calculate the argument of your function (x). However, it should be
double x = startX + i * constantWidth;
Furthermore, your coefficients should be outside of the pow function. Otherwise, they will get exponentiated too. Removing some of the superfluous parentheses makes the formula a lot easier to read. Like this:
double x = startX + i * constantWidth;
totalSum = totalSum
+ firstCoe * Math.pow(x, firstExp)
+ secondCoe * Math.pow(x, secondExp)
+ thirdTerm;
Unrelated to the code: Since you have a simple polynomial, you can calculate the antiderivative analytically and simply evaluate that function instead.
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);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have been trying to make a basic calculator that calculates the mean of 9 numbers. The problem is it always skips the last line.
My code:
/* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package avarage.calc;
import java.util.Scanner;
/**
*
* #author taine
*/
public class AvarageCalc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner input = new Scanner(System.in);
double num1;
double num2;
double num3;
double num4;
double num5;
double num6;
double num7;
double num8;
double num9;
double num10;
double ans;
System.out.print("Enter Number #1:");
num1 = input.nextDouble();
System.out.print("Enter Number #2:");
num2 = input.nextDouble();
System.out.print("Enter Number #3:");
num3 = input.nextDouble();
System.out.print("Enter Number #4:");
num4 = input.nextDouble();
System.out.print("Enter Number #5:");
num5 = input.nextDouble();
System.out.print("Enter Number #6:");
num6 = input.nextDouble();
System.out.print("Enter Number #7:");
num7 = input.nextDouble();
System.out.print("Enter Number #8:");
num8 = input.nextDouble();
System.out.print("Enter Number #9:");
num9 = input.nextDouble();
ans = num1 + num2 + num3 + num4 + num5 + num6 + num8 + num9;
System.out.println("The Average of the numbers you gave is:" + ans / 9);
}
}
When the program runs:
run:
Enter Number #1:20
Enter Number #2:20
Enter Number #3:20
Enter Number #4:20
Enter Number #5:20
Enter Number #6:20
Enter Number #7:20
Enter Number #8:20
Enter Number #9:20
The Average of the numbers you gave is:17.77777777777778
BUILD SUCCESSFUL (total time: 10 seconds)
Your average is incorrect because you are missing num7 in your sum
ans = num1 + num2 + num3 + num4 + num5 + num6 + num8 + num9;
should be
ans = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9;
You have 10 variables, but you calculate average of 9. Is it what you want? Anyway, #the-tom has showed your mistake. You've forgot about num7 variable.
The less lines of code you have the less possibility to get an error.
Probably will be better to do something like that:
double ans = 0;
Scanner input = new Scanner(System.in);
int x = 9 //Or some other number
for(int i = 1; i <= x; i++){
System.out.print("Enter Number #" + i);
ans += input.nextDouble();
}
System.out.println("The Average of the numbers you gave is:" + ans / x);
Now if you need to calculate average of 20 elements, all you need is just set the value of x to 20.