mardi 20 septembre 2016

Trouble with this if-statement

I am coding in Java and using TextPad editor.

I am trying to write code that sets "r" equal to a certain value depending on whether the user is male or female. I have already asked the user to put "1" if they are male and "2" if they are female.

I have set r as a double. D, and weight have been defined by the user earlier in the code.

Here is the code that I am trying to use and it keeps giving me an error saying that I have not defined "r".

if (gender == 1)
r = 0.73D;
if (gender == 2)
r = 0.66D;
else
System.out.println("Please enter 1 or 2 for male or female.");

alcoholAbsored = (3.701*D)/(weight*r);

All of the code compiles until I get to the formula for alcoholAbsorbed and then tells me r is not defined. Technically there is no problem with the if/else statement when I compile but then when I try to use r there becomes a problem. I've ended up using this code for now but this is not really what I want because what if the user puts something other than 1 or 2?

if (gender == 1)
r = 0.73D;
else
r = 0.66D;

alcohol absorbed = (3.701*D)/(weight*r);

Can someone please tell me what I am doing wrong and how I might go about fixing it? Please and thank you!

Aucun commentaire:

Enregistrer un commentaire