Need help on 4/9


#1

i cant figure our how to say
if (computerChoice is in between 0 and 0.333333)


#2

If statements will only run their code blocks if their comparison is true.

if(true){
 return true;
}

So in this case you don't need to worry about if computerChoice is 0 or not.

You only have to check if the value is less than or equal to 0.33.

if(computerChoice <= 0.33){
   computerChoice = "Rock";
}

0 is less than 0.33 so if computerChoice was 0 this if statement would be true and computerChoice would then be set to the string "Rock";

If the value is greater than .33 then the if statement is false and the if statement proceeds to the next part which can be either an else if or just an else.

Hope this helps. =)


#3

In extension on what @polygonner said above

if (computerChoice <= 0.33) {
    computerChoice = "Rock";
}

You can do the other two choices in the same manner as the first with an "else if" as poly also described.

else if (computerChoice <= 0.66) {
    computerChoice = "Paper";
}

The reason you would not need to define the greater than as shown below (Example 1-2), is because you are using the "else if", in written notation (It's below the initial if statement) Remember when you use if else statements and you're broadening your range for the computerChoice that you want to have the more specific number first, and broaden out behind that. (Examples 3-4)

Example 1:
if (computerChoice <= 0.33) {}
else if (computerChoice <= 0.66) {}
else if (computerChoice <= 1) {}

Otherwise while using just "if" statements you would have to define the numbers more precisely.

Example 2:
if (computerChoice >= 0 && computerChoice <= 0.33) {}
if (computerChoice >= 0.34 && computerChoice <= 0.66) {}
etc...

Reason for that is because an "if else" statement reads like a page in a book, from the top down and picks only One of the answers. An "if" statement is read on its own so it has to have it's parameters set, otherwise it will utilize the information in every "if" statement that follows its parameters.

Also, I understand that this was a long tutorial on if statements that was not asked for. But this may be helpful in future coding for efficiency, and greater broadening of understanding code.


#4

Well said @lolman. :smile:

Though I would like to point out for @tylermainia66, that in the Example 1 you provided.

That you would not necessarily need a second else if in this particular case. You could simply use an else.

Example 1:
if (computerChoice <= 0.33) {}
else if (computerChoice <= 0.66) {}
else {}

Overall, great explanation @lolman! :+1:


#5

That's very true. I took into account that there would be more conditions, but in this example there are only three so you are correct in efficiency.