• #### 科普

SCIENCE

#### 英语

ENGLISH

#### 科技

TECHNOLOGY

MOVIE

FOOD

#### 励志

INSPIRATIONS

#### 社会

SOCIETY

TRAVEL

#### 动物

ANIMALS

KIDS

#### 卡通

CARTOON

#### 计算机

COMPUTER

#### 心理

PSYCHOLOGY

#### 教育

EDUCATION

#### 手工

HANDCRAFTS

#### 趣闻

MYSTERIES

CAREER

GEEKS

#### 时尚

FASHION

• 精品课
• 公开课
• 欢迎下载我们在各应用市场备受好评的APP

点击下载Android最新版本

点击下载iOS最新版本

扫码下载译学馆APP

#### 《迪哥Java教程》#17 Java的If语句教程

The Java If Else tutorial - 017

Growing up I was pretty nerdy.

I loved computers, games, and comic books.

When I first started out programming, Iwanted to make games.
10岁的时侯 我做出了我的第一款游戏
I made my first game ever when I was

10 years old based on my favorite comic-book Green Lantern.

The game was really simple. It was a text based game

where you were presented with a choice.

If you made the correct choice for our hero,

you would continue in the game.

Make thewrong one, Green Lantern died.

If you passed all three choices, you wonthe game.

The full game was simple print statements

and the if then statement.

This is whatI’m gonna show you next.

The goals for this lesson

are to understand the if then elsecontrol statement.

As we have in past lessons,

We’ll look at ways that code can go wrong.

This way you know how to identify the

errors in your code when they happen.

We’ll touch upon short-circuit evaluationand when we’re done

looking at the normal if thens,

we’ll quickly look at the very succinct

ternary version. Now that’s great for settingsingle values

without writing the whole if then. So let’sdive in!
if-then是Java中的控制语句
An if then is a Java controlstatement that

behaves exactly how it sounds in English.

If the statement is true,

then do this. The if-then has a key wordand condition.

The keyword”if” starts the controlstatement. It is immediately followed by

the condition to test.

The condition is always enclosed inparentheses.

It’s an error to try to create the if-thenwithout parentheses.

If your condition is true, the Java blockis executed.

False and the Java block is skipped. We can test

if”power is greater than 5″ shoot the badguy.”Power
power如果小于等于5 代码就不会执行
less than or equal to 5″, the code won’trun.

The condition can be a booleanexpression or boolean variable.

The only requirement is anything inside the parentheses must evaluate to true

or false. If you’re coming from a C/C++background,

it’s important to note the condition does not evaluate to 0 or 1.

It must be a Java boolean type.

Since itcould be a boolean expression,

you can do something like this.”If ring ischarged”

is”true” and the”power is greater than 5″ run this block.

Both conditions must be true.

It’s a good idea to use parentheses

inside the condition expression to make this clear. Larger conditions

You can create a boolean value from a complicated expression,

and then just test the value.

In this casewe’re creating a variable called “myCondition”

and setting it to the result of theexpression.

Let’s play with

if then statements so we get this idea clear. Okay

here in our code, I’ve created a variablepower

and set it equal to 6. I’ve also got acondition

where power is greater than 5. Now

if power is greater than 5,

which it is since it’s 6,

we should see this line printed out,”power is greater than 5″.

So we run it

and it prints out”power is greater than 5″.Let’s go back and change power equal

to 4 and see what happens.

In this case, 4 isnot greater than 5

so it should not print out anything.

And nothing’s printed out. Okay.

What do you think will happen in thiscase when power is equal to 5. Well

we run it, and nothing’s printed outagain

because power is not greater than 5.

It’s just equal to 5.

Let’s go to the

case where we want to check if power is equal to 5.

Say for example

we have some case where it’ll only run when power is 5.

We would test that as we saw in theoperators

video with the double equals. We run it, and it printed out”power is greater than 5″,

but really the test was power equal tofive.

Sometimes we want to say

if something is true do this, otherwisedo something else.
Java中就可以这样做 可以再加一个关键字“else”
We have that ability in Java. We can addanother keyword called”else”.

In this example we’re saying, if”power isgreater than 5″,

the do this Java block, otherwise dothe other Java block.

You can also chain these into longer

if then statements. For example, thisblock tests

if”power is greater than 5″ and tests if”power is less than equal to 5″. This is really the same thing as the else

statement from before.

We’re just making the second test explicit. Ifyou use this keyword”else”

without a condition, it will run thefollowing code

block all other if’s are false.

You can add as many else-if’s as you needas well.

Just don’t go crazy or it gets really hardto read!

So what happens when not everything is accounted for? For example

in this case there’s a block for”greater than 5″ and

a block for”less than 5″. What happenswhen”power

equals 5″? Well this just means bothcode blocks are skipped.

Nothing is run. This illustrates theimportance of

checking all the boundaryconditions when working with numbers

and inequalities. If you’re ignoring theequals case,

this would be a really good place to add a comment explaining why.

or somebody else looking at your code is going to be

very confused by your error. Okay goingback to our example

let’s have a second boolean value.

Let’s create a second boolean value “myCondition2”,

where power is less thanor equal to 5.

We can create a second test that is, ifmyCondition2

then print out”power is less than/equal to 5″.

Now we really don’t need to do this.

We won’t necessarily need to be doing

a test for every condition that we want.In this case

there’s only two possible options. Iteither greater than 5

or it’s less than or equal to 5.

So wecan replace the second test with

“else” and it will result in the samething. So in this case
myConditon为真 它会输出“power is greater than 5”
myCondition is true, it’ll print”thepower is greater than 5″.

If it’s false,

then it’ll print out”power is less than orequal to 5″.

It has the exact same effect as

the code with the two if then statements.

Now this example does”greater than” and thenit does
“小于或等于” 但如果我们想分别要每一种情况
“less than or equal”, but if we wanted onecase for each,

one case for”if power is greater than 5″, onecase for

“power is equal to 5″ and one case for”power is less than 5”.

Well we can replace that code

with multiple if then statements.

So in this case we have it”if it’s

this” otherwise”if it’s this” otherwise
if-then语句可以写的很长
“if it’s this”. You can create really longif then statements chains,

but it’s considered bad practice and there isprobably a better

way to do it if you find that you
if-then语句多于4个
for testing and have a case for

more than four if then statements.

Another common source of errors is forgetting braces. As we saw

earlier in the blocks lesson, a statementcan be a block.

Still you want to use braces. Here’s agood example

where you may not get the behavior you’reexpecting.

In this example removing the braces means,

the second line will always be printed.

The indentation is ignored. Going backto the IDE,

we can see this problem in action.

So this code is similar to what we saw in

the blocks lesson where you can create a Java block without brace.

However if you don’t include the braces it makes it kinda weird.

In this case, we have if”power isgreater than 5″, printout

“power is greater than 5”. And the nextline we have
“power is less than 5”
“power is less than 5”.

Now the code is indented like this,

it’s going to be confusing for someone reading it.

They’re going to look at this and think

that these two lines are part of the same

Java block. So when we run it,

it prints out”power is less than 5″.

We might have expected

that that particular line was part of the” power is
power大于5这个条件
greater than 5″

and would be really confused on why thatline ran.

The reason is

“power greater than 5” is it’s own Java block.

We really should be putting in braces tobe really clear

what we intend to happen.

Sometimes you’llhave a test that takes

much longer to evaluate compared to theother tests.

For example you might test if 5 is somewhere

in a list of a million numbers,

and test if b is larger than 4. The test

for b is much easier and quicker than searching through list a million numbers.

If both need to be true always test the easier test first!

In this case, it would be much better to switch the boolean test.

This works because of”short circuitboolean evaluation”.

This means it will stop evaluating theboolean expression

if it knows it will evaluate to false regardless

of the rest of the expression.

Since both need to be true,

there’s no point searching a million numbers

if b is not greater than 4. So

b is 2, Java won’t even try to search.

When youneed to set

a value based on a boolean expression,there is much simpler

code than the full if then.

This is calledthe ternary operator.

It’s an operator we didn’t cover inoperators

because this operator is a control operator,

what that meant yet.

We can write it in a one-line statement.

You simply set your variable to expression.

The first part is the expression totest. Next

we use the question mark to note that this is an if then test.

Finally we put the two possible values

separated by a colon. If the condition istrue

the variable set to the first value,

otherwise it’s set to the second value.

There are no possible ways to handle an else in this expression.

Let’s go play with this in the editor.

The last thing to look at is the ternary operator.

So if we had a variable b

that we wanted to set,

and we wanted to set it to 42

if” power is greater than 5”

and 24 if it is”less than or equal to 5″, wecould write that all on one line.

We don’t have to do a full if then in this case.

We have our ternary operator where”power
“power > 5”是条件
greater than 5″ is our condition,

and then with the ternary operator we’ll set

it to 42 when it’s true,

and 24 when it’s false.

Now like with other conditions

we can also replace our power is greaterthan 5 with

the actual condition.

When we run it,

in this case B is equal to 24

since power is equal to 5. It’s notgreater than five.

Again it’s important to note

that you can not handle an else condition here,

because you can only have two possiblevalues.

You can’t chain with multiple colons or

with some other syntax to say

if then else. It’s always if it’s true

first condition, false if it’s the secondcondition.

There are ways you can really

abuse the if-then statement and create some obnoxious code.

For example you can create this if then code to set a boolean value.

The reason is this issix lines of code,

all to set a boolean value.

Can you guess thebetter form?

I’ll give you a hint. It’s not the ternary operator.

This is what you should do for booleans.In this case

the boolean expression you’re evaluating isa boolean value.

Instead of using an if then to do the logic,

just set it to the value

and you’re done. The best code ever

is the code that you don’t write. So in thislesson

if-then语句以及如何使用它
if then statement and how we use it to control

what code is run in our application.

Welearned how Java short-circuits your

conditions and how this can speed upyour program.

We also learned about the ternaryoperator. And with that,

I’ll see you in the next lesson.

Hey thanks for watch the video!
DeegeU.com上有一个本课程的快速测试
There a quick quiz for this on DeegeU.

com for you to gauge how much you learned.

If you like the videos you are seeing,

please let me know by liking the video

and hitting the subscribe button

for the DeegeU channel on YouTube.

I’d reallyappreciate that.

If you have concerns or questions,

or on DeegeU. com.

There’s a poll onthe front page of DeegeU.

com so you can let me know thetopic covered next.

Thanks for watching, and see you in the next video!

[B]hugue