So, for one of my homework pieces I have to make a Body Mass Index. When I asked my teacher about how to do math within the public void main, he explained that I could just do it in the void main. But when I try It gives me "The Operator * is undefined for the arguments type(s): String, Int".
Here's the code and Instructions:
(Instructions)
Create a new Java project named Your_Name_BMI. Create a class named BMI and write a program using JOptionPane dialog boxes that calculates and displays a person’s body mass index (BMI). The BMI is often used to determine whether a person with a sedentary lifestyle is overweight or under-weight for his or her height. A person’s BMI is calculated with the following formula:BMI = (weight*703) /(height2) Where weight is measured in pounds and height is measured in inches. The program should display messages to the user asking for their weight and height and store the values in appropriately named variables. After making the calculations the program should display a message indicating whether the person has optimal weight, is underweight, or is overweight. A sedentary person’s weight is considered optimal if his or her BMI is between 18.5 and 25. If the BMI is less than 18.5, the person is considered underweight. If the BMI value is greater than 25, the person is considered overweight.
import javax.swing.JOptionPane;
public class Doswell_BMI
{
//declaring important things
static String weight;
static String height;
static int multi;
static int multi2;
static String diagnosis;
static int bmi;
public static void main(String[] args)
{
weight= JOptionPane.showInputDialog("What is your weight?");
height= JOptionPane.showInputDialog("What is your height?");
multi = 703;
multi2 = 2;
bmi = weight * multi / height * multi2;
bmi = Integer.parseInt(diagnosis);
}
}
Yes, you can not multiply Strings as they are so you need to convert to an Integer first
int w = Integer.valueOf (weight);
String cannot be multiply, try this:
bmi = Integer.valueOf(weight) * multi / Integer.valueOf(height) * multi2;
I would advise against using ints to calculate BMI. The equation for calculating BMI in pounds and inches is as follows:
If you’re 5’5” (65”) in height and 150lbs in weight, you would calculate your BMI as follows:
(150lbs / (65 inches²)) x 703 = 24.96.
150 / 65*65 = 0.03550295858 <- This is the reason you want to be using a data type such as double.
weight= JOptionPane.showInputDialog("What is your weight?");
height= JOptionPane.showInputDialog("What is your height?");
These two statements return String values.
You cannot perform mathematical operations to string variables in JAVA.
Hence, you have to convert them to Integer using
either,
Integer.parseInt(weight)
this will convert the string into the primitive type int
or
Integer.valueOf(weight)
this will convert the string into an object of the wrapper class Integer
bmi = weight * multi / height * multi2;
This multiplication is not very accurate as your requirement above is to first multiply the two sections separately and then divide
It is better if you write this as bmi = (weight * multi) / (height * multi2)
so the final statement will be bmi = (weight.Integer.parseInt(weight) * multi) / (height.Integer.parseInt(height) * multi2)
Related
An exercise on my problem worksheet asks us to write a method public static double imperialToKg(double ton, double once, double drachm, double grain) that converts masses given in the imperial system to kg.
We've been given a conversion table for this but what I don't understand, being completely new to java, is HOW can I get my method to differentiate between these input arguments?
For example if I want the method to return the kg value of 11 stone what's to stop it from returning the value of 11 tons (tons being the first argument)
public class W1_E2{
public static double imperialToKg(double ton, double hundredweight, double quarter, double stone, double pound, double once, double drachm, double grain){
ton = 1016.04691;
hundredweight = 50.8023454;
quarter = 12.7005864;
stone = 6.35029318;
ounce = 0.02834952;
drachm = 0.00177185;
grain = 0.0000648;
}
}
I've listed the conversions as variables but I don't know what to do with them...
For 11 stone, you would have to call that like:
returnedFoo = imperialToKg(0,0,0,11,0,0,0);
If you want to call it with a value of 11 tons, you use:
returnedFoo = imperialToKg(11,0,0,0,0,0,0);
For our stone example, try:
On the implementation end, you would use something like:
public static double imperialToKg(double ton, double hundredweight, double quarter, double stone, double pound, double once, double drachm, double grain){
{
double kg = (ton * 1016.04691) + (hundredweight * 50.8023454) + (quarter * 12.7005864) + (stone * 6.35029318) + (ounce * 0.02834952) + (drachm * 0.00177185) + (grain * 0.0000648);
return kg;
}
This is quick and dirty; there is a multitude of better ways to do this, please confirm that the exercise is actually requesting we call the function like this.
Nowhere does it state that you require one method to make all your conversions, but that you require a main method to test your code.
So, make an individual method for each type of conversion required, as an example:
public static double tonToKg(double val){
return val * 1016.04691;
}
To test:
public static void main(String[] args){
System.out.println(tonToKg(11));
}
I write a code in netbeans with the purpose of calculating the area of a pentagon, I wrote it with all the variables of type double. The problem is that when I enter a double to test the code the application prompt a mismatch exception.
I enter an int variable and it works, I have tried to change the code but it doesn't work.
package ejercicios.de.practica.capitulo4_5;
import java.util.Scanner;
public class EjerciciosDePracticaCapitulo4_5 {
public static void main(String[] args) {
// Crear variables
double Area, s, r;
final double PI= 3.1416;
final double TREINTAYSEIS= PI/5;
Scanner input= new Scanner (System.in);
System.out.println(" Enter the lenght from a center to a vertex of the pentagon: ");
r= input.nextDouble();
s= 2*r*(Math.sin(TREINTAYSEIS));
Area= (5*(Math.pow(s,2)))/4*(Math.tan(TREINTAYSEIS));
System.out.println("The area of the pentagon is " + Area);
}
}
If I enter the length from the center to a vertex: 5.5 the area of the pentagon is expected to be 71.92, but in my program, it doesn't accept the double input. I have to enter the int 5 and the result was 37.7007586539534.
It's because your Area equation is not calculating in the sequence you expect. You will need to be a little more specific towards how you want the equation to calculate. Portions of the equation that are contained within brackets are always calculated first so with that in mind:
Instead of:
Area= (5 * (Math.pow(s, 2))) / 4 * (Math.tan(TREINTAYSEIS));
Do this:
Area = (5 * Math.pow(s, 2)) / (4 * Math.tan(TREINTAYSEIS));
Place parentheses around 4 * Math.tan(TREINTAYSEIS). You have a lot of unnecessary bracketing and should get rid of it as I have done since all it does is clutter things up. Also spacing things out can help you see things a little clearer. Personally, if I do double calculations then I try to use all doubles in that calculation:
Area = (5.0d * Math.pow(s, 2.0d)) / (4.0d * Math.tan(TREINTAYSEIS));
On a side note:
If you are only going to use PI to a precision of 4 then perhaps you should consider doing all your calculations to that precision.
I am new to net beans and java and by using net beans GUI, I have to create a linear conversion table. These are the choices: Inches to Centimeters
Feet to Centimeters
Yards to Meters
Miles to Kilometers. The following formulas can be used to convert English Imperial units of measurements to Metric units:
Centimeters = Inches * 2.54
Centimeters = Feet * 30
Meters = Yards * 0.91
Kilometers = Miles * 1.6
It should be created using parameter passing and should return values back to method call.`
This is what I have done so far:
int conversion;
double centimetres = 0,value, metres = 0, kilometres = 0;
conversion=Integer.parseInt(conversioninput.getText());
value=Integer.parseInt(valueinput.getText());
if (conversion==1)
centimetres=value*2.54;
output.setText(""+value+" inches = "+centimetres+ " centimetres");
if (conversion==2)
centimetres=value*30;
output.setText(""+value+" feet = "+centimetres+ " centimetres");
if (conversion==3)
metres=value*0.91;
output.setText(""+value+" yards = "+metres+ " metres");
if (conversion==4)
kilometres=value*1.6;
output.setText(""+value+" miles = "+kilometres+ " kilometres");
I need to include parameter passing and I have no idea how to do it. I am doing an online course and it does not explain anything
What you would want to do is something like this:
public float conversion(int value, int conversion) {
// put your code inside this method
}
Then to call it inside your main method just do:
conversion(40, 2);
It seems like you are new to programming in general, but I would look into enums for the conversion variable. And setup a class something like:
public enum Conversion {
InchToCentimeter,
FeetToCentimeter,
YardsToMeters,
KilometersToMiles
}
Here's a good starting point for enums: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
I'm trying to create a program in Java to calculate the inside angles of any triangle when the user inputs the side lengths. I've seen a few questions similar to this but I can`t get mine to work.
I want this to calculate the angle in degrees but it keeps giving me the wrong answer or not a number (NaN). I've tried putting it all in to one equation in case it was just rounding errors but it just gave the same answer. I've since put it back into this format to make it easier to read.
public class Triangles
{
// variables already declared and user inputs double sideOne, sideTwo, sideThree
threeSq=sideThree*sideThree;
twoSq=sideTwo*sideTwo;
oneSq=sideOne*sideOne;
public static double getAngleOne(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angOne;
angOne = (oneSq + twoSq - threeSq) / (2 * sideOne * sideTwo);
angOne = Math.toRadians(angOne);
angOne = Math.acos(angOne);
angOne = Math.toDegrees(angOne);
return angOne;
}
public static double getAngleTwo(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angTwo;
angTwo = (twoSq + threeSq - oneSq) / (2 * sideTwo * sideThree);
angTwo = Math.toRadians(angTwo);
angTwo = Math.acos(angTwo);
angTwo = Math.toDegrees(angTwo);
return angTwo;
}
public static double getAngleThree(double oneSq, double twoSq, double threeSq, double sideOne, double sideTwo, double sideThree)
{
double angThree;
angThree = (oneSq + threeSq - twoSq) / (2 * sideOne * sideThree);
angThree = Math.toRadians(angThree);
angThree = Math.acos(angThree);
angThree = Math.toDegrees(angThree);
return angThree;
}
}
I`m using the cosine law, but it is not giving me the correct answer. For example, when I input the side lengths as 3, 3 and 3 it gives me 71.68993312052173; when I input 5, 6 and 7 (sides 1, 2 and 3 respectively), I get NaN.
edit:
Thanks for the advice, I have changed all the ints to doubles and my math was the problem (forgot brackets around the oneSq + twoSq - threeSq)
I put up the full revised code but it is still giving the wrong answer, for a triangle with all sides the same, it should return 60 for all three but it`s returning 89.49999365358626.
After correcting the computation of the ratios there still remains one thing to do: Lose the lines
angOne = Math.toRadians(angOne);
at this point, angOne does not contain any angle. If the sides obey the triangle inequality, angOne should at that point contain a number between -1 and 1 that does not need converting.
The ratio of the areas for an equilateral triangle is 0.5. The operations convert-to-radians, acos, convert-to-degrees can be combined as
M*acos(x/M) = M*(pi/2-asin(x/M)),
with the multiplier M=180/pi. Since x/M is small, the result is approximately
M*(pi/2-x/M)=90-x,
resulting in a value close to 89.5, as obtained in your last trial.
Of course, the desired result is M*acos(0.5)=M*(pi/3)=60.
Apart from not using double values, your calculations are probably not correct.
According to cosine law
cosγ = (a^2 + b^2 - c^2)/2ab
so change ang = oneSq + threeSq - twoSq / (2 * sideOne * sideThree); to
double ang = (oneSq + twoSq - threeSq)*1.0 / (2 * sideOne * sideTwo);
When a user enters a whole number, the program runs smoothly, but when the user enters a number that has a decimal at the end, the program crashes.
These are the errors that I get:
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at BMI.main(BMI.java:11)
Here is my code:
import javax.swing.*;
public class BMI {
public static void main(String args[]) {
int height; // declares the height variable
int weight; // declares the weight variable
String getweight;
getweight = JOptionPane.showInputDialog(null, "Please enter your weight in Kilograms"); // asks user for their weight
String getheight;
getheight = JOptionPane.showInputDialog(null, "Please enter your height in Centimeters"); // asks user for their height
weight = Integer.parseInt(getweight); // stores their weight
height = Integer.parseInt(getheight); // stores their height
double bmi; // declares the BMI variable
bmi = weight / Math.pow(height / 100.0, 2.0); // calculates the BMI
double roundbmi; // variable to round the BMI to make it more read-able
roundbmi = Math.round(bmi); // rounds the BMI
JOptionPane.showMessageDialog(null, "Your BMI is: " + roundbmi); // displays the calculated and rounded BMI
}
}
An Integer only recognizes whole numbers. If you want to be able to capture floating point numbers, use either Float.parseFloat() or Double.parseDouble().
To make the answer more complete, let me give you a quick example of why "4.", "4.0", and "4" are represented in two different ways. The first two are considered floating point values (since Java will just assume you mean 4.0 regardless), and how they are represented in memory depends heavily on which datatype you use to represent them - either a float or a double.
A float represents 4.0 using the single-precision floating point standard, whereas a double would represent 4.0 using the double-precision floating point standard. An int represents the value 4 in base-2 instead (so it'd just be 22).
Understanding how numbers are stored internally is critical and key to development, not just with Java. In general, it's recommended to use Double since that gives the larger range of floating point numbers (and higher precision).
You're parsing Integers, which cannot have decimals. Try Double instead.
You are parsing the input as an integer, which cannot have a decimal point in it. You want to parse it as a Double.