Java language basics-flow control statements

Java language basics-flow control statements

Branch structure

The concept of branch structure

  • When you need to make conditional judgments and make choices, use the branch structure.

if branch structure

if (conditional expression) { Statement block; } Copy code

  • Determine whether the conditional expression is true

    => If it is true, execute the statement block

    => If not true, skip the statement block

Case topic

  • Prompt the user to enter two integers, use the if branch structure to find the maximum value and print it out.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter two integers System.out.println( "Please enter two integers:" ); Scanner sc = new Scanner(System.in); int num1 = sc.nextInt(); int num2 = sc.nextInt(); //Use the if branch structure to find the maximum value and print it out int max = num1; if (num2> max) { max = num2; } System.out.println( "The maximum value is:" + max); } } Copy code

if else branch structure

if (conditional expression) { Statement block 1 ; } else { Statement block 2 ; } Copy code

  • Determine whether the conditional expression is true

    => If it is true, execute statement block 1 => If it is not true, execute statement block 2

Case topic

  • Prompt the user to enter an integer, use the if else branch structure to determine whether the integer is negative or non-negative and print it.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter an integer System.out.println( "Please enter an integer:" ); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); //Use the if else branch structure to determine whether the integer is negative or non-negative and print if (num >= 0 ) { System.out.println(num + "is a non-negative number" ); } else { System.out.println(num + "is a negative number" ); } } } Copy code
  • Use the if else branch structure to determine whether the integer is positive, negative, or zero.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter an integer System.out.println( "Please enter an integer:" ); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); //Use the if else branch structure to determine whether the integer is positive, negative, or zero if (num >= 0 ) { if (num> 0 ) { System.out.println(num + "is a positive number" ); } else { System.out.println(num + "is zero" ); } } else { System.out.println(num + "is a negative number" ); } } } Copy code

if else if else branch structure

if (conditional expression 1 ) { Statement block 1 ; } else if (conditional expression 2 ) { Statement block 2 ; } else { Statement block n; } Copy code

  • Determine whether conditional expression 1 is established

    => If it is true, execute statement block 1

    => If it is not true, then judge whether expression 2 is true

    ----- => If it is true, execute statement block 2

    ----- => If not, execute statement block n

Case topic

  • Calculate personal income tax based on the salary entered by the user and print it out. One of the tax thresholds is:

    5000 yuan, the specific rules are as follows:

/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter their personal salary System.out.println( "Please enter your salary:" ); Scanner sc = new Scanner(System.in); int salary = sc.nextInt(); //Use the if else if else branch structure to determine the salary range and calculate the corresponding personal income tax //Personal income tax formula: taxable income this month * corresponding tax rate-quick deduction double salaryPrice = 0.0 ; if (salary <= 5000 ) { System.out.println( "No tax required" ); } else if (salary <= 8000 ) { salaryPrice = (salary- 5000 ) * 0.03 ; } else if (salary <= 17000 ) { = salaryPrice (the salary - 5000 ) * 0.1 - 210 ; } else if (salary <= 30000 ) { = salaryPrice (the salary - 5000 ) * 0.2 - 1410. ; } //Print the final calculation result System.out.println( "The final personal income tax is:" + salaryPrice); } } Copy code
  • Taxi billing method: Calculated by adding the mileage and waiting time.

    The mileage is 13 yuan for the first 3 kilometers, 2 yuan per kilometer for the portion exceeding 3 to 15 kilometers, and 3 yuan per kilometer for the portion above 15 kilometers.

    1 yuan every 2 minutes while waiting, no money is needed for the shortfall.

    Enter the number of kilometers and waiting seconds, and output the fare.

    16 kilometers, waiting for 290 seconds, fare = 13 + (15-3)*2 + (16-15)*3 + 1 = 41

/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter the number of kilometers and the number of seconds to wait System.out.println( "Please enter the number of kilometers and the number of seconds to wait:" ); Scanner sc = new Scanner(System.in); int km = sc.nextInt(); int sec = sc.nextInt(); //Calculate the corresponding mileage fee based on the number of kilometers int kmPrice = 0 ; if (km <= 3 ) { kmPrice = 13 ; } else if (km < 15 ) { kmPrice = 13 + (km- 3 ) * 2 ; } else { kmPrice = 13 + (km- 3 ) * 2 + (km- 15 ) * 3 ; } //Calculate the corresponding waiting fee according to the number of seconds waiting int secPrice = sec/150 ; //Calculate the total cost and print int sumPrice = kmPrice + secPrice; System.out.println( "The total cost of this taxi is:" + sumPrice); } } Copy code
  • Prompt the user to enter the test score, use the if-else if-else branch structure to determine the level and print it.

    [90 ~ 100]-Level A

    [80 ~ 89] - Level B

    [70 ~ 79] - Level C

    [60 ~ 69] - Level D

    [0 ~ 59] --- Level E

/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter the test score System.out.println( "Please enter the test score:" ); Scanner sc = new Scanner(System.in); int score = sc.nextInt(); //Use the if-else if-else branch structure to determine the level and print if (score >= 90 && score <= 100 ) { System.out.println( "Level A" ); } else if (score >= 80 ) { System.out.println( "Level B" ); } else if (score >= 70 ) { System.out.println( "Level C" ); } else if (score >= 60 ) { System.out.println( "Level D" ); } else { System.out.println( "Level E" ); } } } Copy code

switch case branch structure

switch (variable/expression) { case literal value 1 : Statement block 1 ; break ; case literal 2 : Statement block 2 ; break ; ... default : Statement block n; } Copy code
  • The data types supported in switch() are: byte , short , char , int , enumerated types are supported from jdk1.5 , and String types are supported from jdk1.7 .

Cyclic structure

The concept of cyclic structure

  • If you want to repeatedly execute a piece of code in a Java program, you need to use a loop structure.

for loop

for (initialization expression; conditional expression; modify initial value expression) { Loop body; } Copy code

Case topic

  • Use a for loop to print all odd numbers from 1-100, using three methods.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Use a for loop to print all odd numbers from 1-100 //Method one for ( int i = 1 ; i <= 100 ; i++) { if (i% 2 != 0 ) { System.out.println( "i = " + i); } } System.out.println( "---------------------" ); //Method two for ( int i = 1 ; i <= 100 ; i += 2 ) { System.out.println( "i = " + i); } System.out.println( "---------------------" ); //Method three for ( int i = 1 ; i <= 50 ; i++) { System.out.println( "i = " + ( 2 * i- 1 )); } } } Copy code
  • Use a for loop to achieve accumulation: 1+2+...+10000=? and finally print it out.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Use for loop to achieve accumulation: 1+2+...+10000=? Finally print out int sum = 0 ; for ( int i = 1 ; i <= 10000 ; i++) { sum += i; } System.out.println( "sum = " + sum); } } Copy code
  • Use a for loop to print all the daffodils in three digits.

    The "number of daffodils" is an integer whose value is equal to the sum of the cubes of the digits.

    Such as: 153=1^3+5^3+3^3

/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Use for loop to print all daffodil numbers in three digits for ( int i = 100 ; i <= 999 ; i++) { //split hundreds digits int num1 = i/100 ; //split tens digits int num2% I = 100/10 ; //digit split int num3% I = 10 ; //Determine whether the number is equal to the cube sum of each digit if ((num1*num1*num1 + num2*num2*num2 + num3*num3*num3) == i) { System.out.println( "i = " + i); } } } } Copy code

continue keyword

  • The continue statement is used in the loop body to end this loop and start the next loop.

Case topic

  • Use a for loop to print an integer between 1-20, if it encounters a multiple of 5, skip it without printing.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Use a for loop to print an integer between 1-20, if it encounters a multiple of 5, skip it without printing for ( int i = 1 ; i <= 20 ; i++) { if (i% 5 == 0 ) { //skip this loop continue ; } System.out.println( "i = " + i); } } } Copy code

break keyword

  • Break is used to exit the current statement block, and break is used to exit the loop in the loop body.
  • for(;;) -This kind of loop without loop conditions is called an infinite loop , commonly known as an " infinite loop ".

Case topic

  • The user is continuously prompted to enter the chat content and output until the user enters "bye" to end the chat.
/* Process control */ import java.util.Scanner; public class ProcessControlTest { public static void main (String[] args) { //Constantly prompt the user to enter the chat content and output until the user enters "bye" to end the chat Scanner sc = new Scanner(System.in); for (;;) { System.out.println( "Please enter the chat content:" ); String str = sc.next(); //Determine whether the input content is "bye" if (str.equals( "bye" )) { System.out.println( "Chat End" ); break ; } System.out.println( "The chat content is:" + str); } } } Copy code
  • Guess the number game

    Randomly generate the number n (1-100), wait for the user to input the guess data, compare the output according to the user's input, guess the big one, guess the small one, guess the correct one, and end the game if the user guesses the correct one.

/* Process control */ import java.util.Scanner; import java.util.Random; public class ProcessControlTest { public static void main (String[] args) { //Randomly generate numbers (1-100) Random ra = new Random(); int temp = ra.nextInt( 100 ) + 1 ; Scanner sc = new Scanner(System.in); for (;;) { //prompt the user to enter the guessed number System.out.println( "Please enter the guessed number" ); int num = sc.nextInt(); if (num> temp) { System.out.println( "Guess it big" ); } else if (num <temp) { System.out.println( "Guess it is small" ); } else { System.out.println( "Guessed right" ); //End the loop break ; } } } } Copy code

Double for loop format

for (initialization expression 1 ; conditional expression 2 ; modify initial value expression 3 ) { for (initialization expression 4 ; conditional expression 5 ; modify initial value expression 6 ) { Loop body; } } Copy code

Features of double for loop

  • The outer loop is used to control the number of rows printed, the inner loop is used to control the number of columns printed, the outer loop is changed, and the inner loop runs a circle from beginning to end.

Case topic

  • Use double for loop to print the following patterns separately

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copy code
/* Process control */ import java.util.Scanner; import java.util.Random; public class ProcessControlTest { public static void main (String[] args) { //Pattern one for ( int i = 0 ; i < 5 ; i++) { for ( int j = 0 ; j < 5 ; j++) { System.out.print( "* " ); } System.out.println(); } System.out.println( "---------------------" ); //Pattern two for ( int i = 0 ; i < 5 ; i++) { for ( int j = 0 ; j <= i; j++) { System.out.print( "* " ); } System.out.println(); } System.out.println( "---------------------" ); //Pattern three for ( int i = 0 ; i < 5 ; i++) { for ( int j = 5 ; j> i; j--) { System.out.print( "* " ); } System.out.println(); } System.out.println( "---------------------" ); //Pattern four for ( int i = 0 ; i < 5 ; i++) { for ( int j = 4 ; j> i; j--) { System.out.print( "" ); } for ( int k = 0 ; k <(i * 2 + 1 ); k++) { System.out.print( "* " ); } System.out.println(); } } } Copy code
  • Use a for loop to print the nine-nine-nine multiplication table.
/* Process control */ import java.util.Scanner; import java.util.Random; public class ProcessControlTest { public static void main (String[] args) { //Use a for loop to print the nine-nine-nine multiplication table for ( int i = 1 ; i <= 9 ; i++) { for ( int j = 1 ; j <= i; j++) { System.out.print(j + "*" + i + "=" + i*j + "" ); } System.out.println(); } } } Copy code

The break keyword jumps out of multiple loops

  • To exit the outer loop body, you need to use the labeling method.
label: for (...) { for (...) { break label; } } Copy code

Case topic

  • Use double for loop to print all prime numbers between 2-100

    When a number can only be divisible by 1 and itself, the number is called a prime number or prime number.

/* Process control */ import java.util.Scanner; import java.util.Random; public class ProcessControlTest { public static void main (String[] args) { //Use a double for loop to print all prime numbers between 2-100 for ( int i = 2 ; i <= 100 ; i++) { //Declare whether a boolean variable flag is prime boolean flag = true ; for ( int j = 2 ; j <= Math.sqrt(i); j++) { if (i% j == 0 ) { flag = false ; break ; } } //print prime numbers if (flag) { System.out.println( "i = " + i); } } } } Copy code

while loop

while (conditional expression) { Loop body; } Copy code

Case topic

  • Use the while loop to calculate the sum of the harmonic sequence and print it, that is: 1/1 + 1/2 + ... + 1/n.
/* Process control */ import java.util.Scanner; import java.util.Random; public class ProcessControlTest { public static void main (String[] args) { //Use the while loop to calculate the sum of the harmonic sequence and print it, that is: 1/1 + 1/2 + ... + 1/n //prompt the user to enter an integer System.out.println( "Please enter an integer:" ); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); double sum = 0.0 ; int i = 1 ; while (i <= num) { sum += 1.0/i; i++; } //Print the calculation result System.out.println( "The calculation result is:" + sum); } } Copy code

Comparison of while loop and for loop

  • The while loop is suitable for situations where the loop conditions are clear but the number of loops is not clear.
  • The for loop is suitable for situations where the number or range of loops is clear.
  • while(true) is equivalent to for(;;) both means infinite loop .

Case topic

  • The user is prompted to enter a positive integer with any number of digits and then output in reverse.
/* Process control */ import java.util.Scanner; import java.util.Random; public class ProcessControlTest { public static void main (String[] args) { //Prompt the user to enter a positive integer with any number of digits and then output in the reverse direction System.out.println( "Please enter a positive integer with any number of digits :" ); Scanner sc = new Scanner(System.in); int num = sc.nextInt(); //Reverse output int res = 0 ; int temp = num; while (temp> 0 ) { res = res * 10 + temp% 10 ; temp/= 10 ; } //Print the result System.out.println(num + "The result of reverse output is:" + res); } } Copy code

do while loop

do { Loop body; } while (conditional expression); copy the code
  • The do-while loop is mainly used in situations where the body of the loop is executed at least once.