Java selection and looping constructs a detailed tutorial

A selecting structure (6 kinds)

1, single-branch if statement

if(condition){

  statements;

}

If the Boolean expression condition is true, statements statement is executed, or if the statement after the structure to execute.

Example 1

package com.baidu.czy;

import java.util.Scanner;

public class CheckNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println ( "Please enter an integer:" );
         int NUM = sc.nextInt ();
         IF (NUM == 0 && NUM. 5%. 6% == 0 ) {
            System.out.println (NUM + "can be simultaneously divisible by 5 and 6" );
        }
        if (num == 0 || 5% or 6% == 0 ) {
            System.out.println (NUM + "be divisible by 5 or 6" );
        }
        if (whether whether ^ 0% 6% 2 == == 0 ) {
            System.out.println (NUM + "can only be divisible by 5 or 6" );
        }

    }
}

2, if-else statement branch bis

Example 2

import java.util.Scanner;
public class AdditionQuiz {
    public static void main(String[] args) {
        int number1 = (int)(Math.random()*10);         // [0.0-1.0)
        int number2 = (int)(Math.random()*10);
        System.err.print(number1 + "+" + number2 +"=");
        Scanner input = new Scanner(System.in);
        int answer = input.nextInt();
        if(answer ==(number1+number2)){
            System.out.println ( "Congratulations, you got it!" );
        }else{
            System.out.println ( "I'm sorry, got it wrong!" );
            System.out.println(number1 +"+"+number2 +"="+(number1+number2));
        }
    }

}

3, nested if statements and multiple branches if-else statement

Example 3

package com.baidu.czy;

import java.util.Scanner;
/ *
1, member variables: no initialization.
No need to initialize the member variable, the default initialization process of creating the instance.

Added: modifications to the final member variables. You must be explicit initialization assignment.

2, the inside of the method of formal parameters: without initialization.
Java class methods, mechanisms belonging passed by value, when the calling method to complete the transmission parameters, rather parameter is initialized.

3, local variables: must be initialized.
And member variables, local variables must be initialized show, to be able to use.
 */

public class ScoreLevel {
    public static void main(String[] args) {

        String level = null;
        Scanner sc = new Scanner(System.in);
        Of System.out.print ( "Enter Results:" );
         Double Score = sc.nextDouble ();
         IF (Score> 100 || Score <0 ) {
            System.out.println ( "Enter the result is not correct." );
        }else if (score >= 90){
            Level = "excellent" ;
        }else if (score >= 80){
            Level = "good" ;
        }else if (score >= 70){
            Level = "medium" ;
        }else if (score >= 60){
            Level = "pass" ;
        }else {
            Level = "fail" ;
        } 
        System.out.println ( "Your achievement level is:" + Level);
    }
}

4, the conditional operator

The conditional operator is the only ternary operator Java

condition ?  expression1 : expression2

If the condition is true, execution expression1, expression2 otherwise execution

5, switch sentence structure

switch(expression){

  case value1:

    statements     [break];

    case value2:

    statements     [break];

  . . . . .  . . . .. 

  [default:

   statements ]

}

note:

(. 1) expression is an expression whose value must be a byte, short, int, char, String, enum, while expression type must match the type of value.

(2) break statement is optional, and the case of the calculated value of expression matching, if the matching case statement following clause is executed, until it encounters break statement;

  If not match, the default statement block is executed; if the both do not match and no default statement, the switch directly out structure.

Example 4

package com.baidu.czy;

import java.util.Scanner;

public class SwitchDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println ( "Enter the year:" );
         int   year = sc.nextInt ();
        System.out.println ( "Please enter the month:" );
         int month The = sc.nextInt ();
         int numDays = 0 ;
         Switch (month The) {
             Case . 1: Case . 3: Case . 5 :
             Case . 7: Case . 8: Case 10 :
             Case 12 :
            numDays = 31;
            break;
            case 4: case 6: case 9:case 11:
            numDays = 30;
            break;
            case 2:
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
                    numDays = 29;
                }else {
                    numDays = 28;
                }
                break;
            default:
                    System.out.println ( "Illegal month" );
                     BREAK ;
        } 
        System.out.println ( "the number of days in the month is:" + numDays);

    }
}

Second, the loop structure (four kinds)

1, while loop ( "When the loop")

Generally used in the case of cycle times of uncertainty

Case

package com.baidu.czy;

import java.util.Scanner;

public  class guessNumber {
     public  static  void main (String [] args) {
         // randomly generated numbers 100 to 200 
        int Magic = ( int ) (100 + Math.random () * 101 );
        Scanner sc = new Scanner(System.in);
        System.out.println ( "Please enter the number you guess:" );
         int GUESS = sc.nextInt ();
         the while (GUESS =! Magic) {
             IF (GUESS> Magic) {
                System.out.println ( "You guess the big" );
            }else {
                System.out.println ( "You guessed smaller" );
            }
            // proceeds to the next 
            GUESS = sc.nextInt ();
        } 
        System.out.println ( "Congratulations, you got it \ n This number is:!" + Magic);
    }
}

2, do-while loop ( "type until the" loop)

Is the difference between a while loop, do-while loop executed at least once.

Case

import java.util.Scanner;
public class DoWhileDemo {
    public static void main(String[] args) {
       double sum = 0,avg = 0;
       int n = 0;
       double number;
       Scanner input = new Scanner(System.in);
       do{
           Of System.out.print ( "Enter a number (input 0 End):" );
           number = input.nextDouble();
           if(number != 0){
              sum = sum + number;
              n = n + 1;
           }
       }while(number!=0);
       avg = sum / n;
       System.out.println("sum = "+ sum);
       System.out.println("avg = "+ avg);
    }
}

3, for circulation

Generally used in the case where a fixed number of cycles

Cases print multiplication table

public  class NineTable {

    public static void main(String[] args) {
        for(int i = 1; i < 10; i++){
            for(int j = 1; j <=i; j++){
                System.out.print(i +"*"+j + "="+i*j + "  ");
            }
            System.out.println();
        }
    }
}

 Note: for all or part of the cycle can be empty, but can not be omitted semicolon.

As for (;;) {

}

4, enhanced for loop

Mainly used to iterate over the array elements and collections

The general format

for(type  identifier: expression){

  // loop

}

Meaning the cycle: each element identifier (an array or collection) of the expression, execution of a loop statement.

       type or group index of the set of element types; expression The subject must be an array or collection.

For example: for-loop with the enhanced requirements of the elements in the array and marks

double sum = 0;

for(double score:marks){

  sum = sum + score;

}

Limitations of using the enhanced for loop: only sequential access an array or a collection of elements.

Guess you like

Origin www.cnblogs.com/my-program-life/p/11002965.html