Java Branching Structure-if...else/switch

Source: Internet
Author: User
Tags case statement java se

Java Branching Structure-if...else/switch

Sequential structures can only be executed sequentially, not judged and chosen, so branching structures are required.

There are two types of branching structures in Java:

    • if statement
    • Switch statement
If statement

An If statement contains a Boolean expression and one or more statements.

Grammar

The syntax for the IF statement is as follows:

if (Boolean expression) {   // If the Boolean expression is true the statement to be executed }

If the value of the Boolean expression is true, the code block in the IF statement is executed, otherwise the code after the IF statement block is executed.

Test.java File Code:
 Public class Test {    publicstaticvoid  main (String args[]) {      int x = Ten;        if (x < ) {         System.out.print ("This is the IF statement");    }}}

The results of the above code compilation run as follows:

if statement

If...else statements

The If statement can be followed by the Else statement, and if the Boolean expression value of the If statement is false, the ELSE statement block is executed.

Grammar

The usage of If...else is as follows:

if (Boolean expression   ) {// If the value of the Boolean expression is true}else{   //  If the value of the Boolean expression is False}

Instance Test.java file code:
 Public class Test {    publicstaticvoid  main (String args[]) {      int x = ;        if (x < ) {         System.out.print ("This is an if statement");      } Else {         System.out.print ("This is the Else statement")      ;    }}}

The results of the above code compilation run as follows:

Else statement

If...else if...else Statements

The If statement can be followed by a elseif...else statement, which detects a variety of possible scenarios.

When using the If,else if,else statement, the following points need to be noted:

    • The IF statement has at most 1 else statements, and ELSE statements after all ElseIf statements.
    • An If statement can have several ElseIf statements, which must precede the Else statement.
    • Once one of the else if statements detects true, the other else if and else statements will skip execution.
Grammar

The IF...ELSE syntax format is as follows:

if (Boolean expression 1)   {// If the value of Boolean expression 1 is true execution code }elseif(boolean expression 2) {    // if the value of the Boolean expression 2 is true, the code is executed } Else if (Boolean expression 3   ) {// If the value of Boolean expression 3 is true execution code }else  {   //  If none of the above Boolean expressions execute code for true }

Instance Test.java file code:
 Public classTest { Public Static voidMain (String args[]) {intx = 30; if(x = = 10) {System.out.print ("Value of X is 10"); }Else if(x = = 20) {System.out.print ("Value of X is 20"); }Else if(x = = 30) {System.out.print ("Value of X is 30"); }Else{System.out.print ("This is the Else statement"); }   }}

The results of the above code compilation run as follows:

Value of X is 30

Nested IF...ELSE statements

It is legal to use nested IF...ELSE statements. This means that you can use an if or ElseIf statement in another if or ElseIf statement.

Grammar

The nested IF...ELSE syntax format is as follows:

if (Boolean expression 1) {   //// If the value of Boolean expression 1 is true execution code   if(boolean expression 2) {      // / If the value of Boolean expression 2 is true execution code    }}

You can nest else if...else like an if statement.

Instance Test.java file code:
 Public class Test {    publicstaticvoid  main (String args[]) {      int x = ;       int y = ten;        if (x = = ) {         if(y = = ) {             System.out.print ("x = y = ten");          }       }    }}

The results of the above code compilation run as follows:

X = + and Y = 10

Switch statement

The switch statement determines whether a variable is equal to a value in a series of values, and each value is called a branch.

Grammar

The switch syntax format is as follows:

Switch(expression) { CaseValue://Statement        Break;//options available     CaseValue://Statement        Break;//options available//you can have any number of case statements    default://options available//Statement}

The switch statement has the following rules:

    • The variable type in the switch statement can be: Byte, short, int, or char. Starting with Java SE 7, switch supports string types, and case labels must be string constants or literals.

    • A switch statement can have more than one case statement. Each case is followed by a value and a colon to compare.

    • The data type of the value in the case statement must be the same as the data type of the variable, and can only be constants or literal constants.

    • When the value of a variable is equal to the value of the case statement, the statement after the case statement starts executing until the break statement appears and jumps out of the switch statement.

    • The switch statement terminates when a break statement is encountered. The program jumps to the statement following the switch statement execution. The case statement does not have to contain a break statement. If no break statement appears, the program continues to execute the next case statement until a break statement appears.

    • A switch statement can contain a default branch, which must be the last branch of a switch statement. Default is executed when there is no case statement with the value equal to the value of the variable. The default branch does not require a break statement.

Instance Test.java file code:
 Public classTest { Public Static voidMain (String args[]) {//char grade = Args[0].charat (0);      CharGrade = ' C '; Switch(grade) { CaseA: System.out.println (Excellent);  Break;  CaseB :          CaseC: System.out.println (Good);  Break;  CaseD: System.out.println (Failed);  CaseF: System.out.println ("You need to work harder.");  Break; default: System.out.println ("Unknown Level"); } System.out.println ("Your rank is" +grade); }}

The results of the above code compilation run as follows:

Well your rank is C

List of Notes
  1. Using the preceding variables and the For loop, and if knowledge, the program's function is to enter a diamond consisting of an * number in the console. Take a look at the following code:

     Public classDemo2 {//The following is the ascending code     Public voidPrit1 (floatc) {floatp = C/2;//Sort Ascending        floatD//declaring row number variables        floatE//declare a variable that prints an * number        floatF//declare a variable that prints a space        floatR//Declare ascending sort        floats = c% 2;//Take the mold        if(s = = 0) {System.out.println ("The data you entered cannot form a diamond structure"); } Else {             for(d = 1; d <= p; d++) {                 for(f = p; f >= D; f--) {System.out.print (" "); }                 for(e = 1; e <= d * 2-1; e++) {                    if(E = = 1 | | e = = d * 2-1) {System.out.print ("*");//if it is the first number and the last number, enter *}Else{System.out.print (" ");//Otherwise, enter a space}} System.out.println (); }        }    }    //here is the code in reverse print     Public voidPrit2 (floatm) {floatI//declaring row number variables        floatJ//declare a variable that prints an * number        floatK//declare a variable that prints the number of spaces        floatn = m/2 + 1;//reverse Order        floato = m% 2;//m modulus        if(o = = 0) {System.out.print (""); } Else {             for(i = 1; I <= n; i++)//line number loop;            {                //Print a space before printing the * number;                 for(k = 0; k < i-1; k++) {System.out.print (" "); }                //The following is a loop that prints the number of * numbers;                 for(j = (n-k) * 2-2; J >= 1; j--)//a loop that prints the number of * numbers;                {                    if(j = = (n-k) * 2-2 | | j = = 1) {System.out.print ("*"); } Else{System.out.print (" "); }                }                //after printing the * number of line printing;System.out.println (); }        }    }     Public Static voidMain (string[] args) {Demo2 a=NewDemo2 (); floatb = 11;//determines whether a diamond can be formed, depending on the number of rows. If the cardinality row can enter the corresponding diamond, if it is an even row then output "The data you entered cannot form a diamond structure";a.prit1 (b);    A.prit2 (b); }}
  2. Place the diamond that needs to be printed in a square, the console prints a a*a area, finds the function where the diamond edge is located, prints "*" on the edge, and the other dots print "". Instead of distinguishing between ascending and descending, see the code:

     Public classdraw{intb;//A is the number of diamond rows to be generated    intH//h is a parameter in a method, and is also the number of rows    intI,j;//I j is the cyclic structure parameter     Public voidDrawinth) {         for(i = 1; I <= h; i++) {//print row by line             for(j = 1;j <= h;j++) {//the number of prints per line is consistent with the number of rows//The following statement is a diamond four-edged function, a coordinate point on the edge, printing *, otherwise printing a space                if(j = = (H + 3)/2-i | | j = = (h-1)/2 + i | | j = i-(h-1)/2 | | j = = (3 * H + 1)/2-i) {System.out.print ("*"); }Else{System.out.print (" ");        }} System.out.println (); //line I print out line break        }    }     Public Static voidMain (string[] args) {//Static MethodsDraw B =NewDraw ();//Initialize Method        intA = 35;//assigning and executing the Draw methodB.draw (a); }}

Java Branch Structure-if...else/switch

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.