From http://www.cnblogs.com/ggjucheng/archive/2012/12/16/2820834.html
English from http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html
If-then statement
If-then statements are the most basic control flow statements. It tellsProgram, Only when the test computation returns trueCode. For example,Bicycle
You can use the brake deceleration function only when the bicycle is in motion.Applybrakes
One possible implementation of the method is as follows:
Void applybrakes () {// the "if" clause: bicycle must be moving if (ismoving) {// The "then" clause: decrease current speed currentspeed --;}}
When this test is calculated as false (indicating that the bicycle is not in motion), The if-then statement control code jumps to the end.
Also, the braces are optional and there is no braces. The "then" clause contains only one statement.
Void applybrakes () {// same as abve, but without braces if (ismoving) currentspeed --;}
Deciding when to omit braces is a matter of personal taste. Ignore braces, which may cause the code to be weak. If the second statement is to be added to the "then" clause, a common error will forget to add the new braces. The compiler cannot capture errors in this case, and the program will produce incorrect results.
If-then-else statement
When the "if" clause is calculated as false, the if-then-else statement provides the second path for program execution. You canIn the applybrakes method, the if-then-else statement is used. When the bicycle is not in motion, the system requests the brakes to slow down and execute some actions. In this case, this behavior simply outputs an error message saying that the bicycle has stopped.
Void applybrakes () {If (ismoving) {currentspeed --;} else {system. Err. println ("the bicycle has" + "already stopped! ");}}
The following program,Ifelsedemo, based on the score value, assigns a level: score over 90% is A, score over 80% is B, and so on.
Class ifelsedemo {public static void main (string [] ARGs) {int testscore = 76; char grade; If (testscore> = 90) {grade = 'a ';} else if (testscore> = 80) {grade = 'B';} else if (testscore> = 70) {grade = 'C';} else if (testscore> = 60) {grade = 'D';} else {grade = 'F';} system. out. println ("grade =" + grade );}}
The output result of the program is:
Grade = C
You may notice that the value of testscore can meet multiple expressions in the composite statement:76> = 70
And76> = 60. However, once a condition is met, the appropriate statement will be executed (grade = 'C';), and the remaining conditions will not be calculated.