14.0/Jump statement: break, continue(Java)

Table of Contents

Foreword:

1. bear statement

2. continue statement

3. Summary:

14.1Random number (Random) in JAVA

1. Life applications of random numbers:

2. How to use random numbers:

3. Get random numbers

Detailed example 4:


Foreword:

In the loop structure, we have also come into contact with some forms of infinite loops. So what should I do if I want to jump out of the loop early during the loop process?

Whether it is a while loop or a for loop, there are two special statements that can be used

Here you need to use jump statements: break and continue

  • break function: jump out and end the execution of the current loop

  • continue function: end this cycle and enter the next cycle

1. Beark statement

During the loop, you can use the break statement to jump out of the current loop.

int sum = 0;
for (int i=0;;i + + ) {
    sum = sum + i;
    if (i == 100) {
    break; // Jump out of the current loop
    }
}
System.out.println(sum); // Output result: 5050

The for loop does not set the detection condition for loop exit. However, if is used inside the loop, if i==100, the loop is exited through break.

The break statement is usually used in conjunction with the if statement. Special attention should be paid to the fact that break only jumps out of the loop where it is.

Example 1:

// 1. break: jump out and end the execution of the current loop.
// Scenario: If you have a wife again and you make a mistake, your wife punishes you by saying: 5 sentences of "I love you"
// When I got to the third sentence, I softened my heart and asked you to stop talking.
for (int i = 1; i <= 5; i + + ) {
    System.out.println("I love you:" + i);
    if(i==3){
        // It means that you have finished the third sentence and you are soft-hearted.
        break; // Jump out and end the execution of the current loop.
    }
}

2. continue statement

Note: break will jump out of the current loop, that is, the entire loop will not be executed.

Continue ends this loop early and continues directly to the next loop.

int sum = 0;
// Calculate the sum of all odd numbers from 1 to 100
for(int i=0; i<=100; i + + ) {
    if (i % 2 == 0) {
        System.out.println(i);
        continue; //End this loop
    }
    sum = sum + i;
    }
System.out.println(sum); //Output result: 2500

Pay attention to the effect of the continue statement. When i is an even number, continue will end this loop and the sum=sum + i accumulation statement will not be executed.

In multi-layer nested loops, the continue statement also ends the current loop.

Example 2:

// 2. continue: Jump out of the current execution of the current loop and directly enter the next execution of the loop.
// Scenario: If you have a wife and you make a mistake, your wife punishes you by washing the dishes for 5 days.
// On the third day, you performed very well and didn't have to wash the dishes on the third day, but if you don't understand your hatred, you still have to continue on the fourth day.
for (int i = 1; i <= 5; i + + ) {
    if(i == 3) {
        // It’s already the third day, so there’s no need to wash it on the third day.
        continue;
    }
    System.out.println("Washing dishes:" + i);
}

3. Summary:

break and continue cannot be used everywhere!

14.1 Random Numbers (Random) in JAVA

1. Life applications of random numbers:

Generating random numbers is practical in many scenarios.

For example, in class, you can write a random roll call device to call on students to answer questions;

For another example, random draws can be held at the company’s annual meeting. double color ball

2. How to use random numbers:

Scanner input class.

In fact, Java has already provided us with the function of generating random numbers. A class called Random is provided in the JDK. We only need to call the function provided by the Random class.

Steps for usage:

1. Guide package

import java.util.Random;

2. Create objects

Random r = new Random();

3. Get random numbers

int number = r.nextInt(10);
//The range of obtaining data: [0,10) includes 0 and excludes 10

//Title: Get a random number between 1 and 100
//Get a random number between 1 and 100
        //Create object
        Random r = new Random();

        for (int j = 0; j < 10; j + + ) {
            //Get random number
            int i = r.nextInt(100);//The current range is 0~99
            i + = 1;//The current range is 1~100
            System.out.println(i);
        }
Detailed example 4:

//Goal: Master the steps to use Random to generate random numbers.
// 1. Guide package. import java.util.Random; (idea will complete it automatically)
import java.util.Random;
public class RandomDemo1 {
    public static void main(String[] args) {
        // 2. Create a Random object for generating random numbers.
        Random r = new Random();
        // 3. Call the function provided by Random: nextInt to get a random number.
        for (int i = 1; i <= 20; i + + ) {
            int data = r.nextInt(10); // 0 - 9
            System.out.println(data);
        }
    }
}

Detailed Example 5:

Requirements:
Randomly generate a number between 1 and 100, prompting the user to guess. If the guess is too big, the tip is too big, if the small guess is too small, the tip will be too small until the guess is correct and the game ends.

analyze:
1. First randomly generate a data between 1-100.
Who can help you generate random numbers? Do I need to use Random?
2. Define an infinite loop so that users can keep guessing.
Where does the data that users guess come from? Do I need to use Scanner?

3. In an infinite loop, compare the data entered by the user with a random number each time
If it is larger than a random number: it prompts you to guess it.
If it is smaller than a random number: it prompts that the guess is smaller.
If it is the same as the random number: Congratulations, you guessed correctly.


import java.util.Random;
import java.util.Scanner;

public class RandomTest2 {
    public static void main(String[] args) {
        // 1. Randomly generate a number between 1-100 as the winning number.
        Random r = new Random();
        int luckNumber = r.nextInt(100) + 1;

        // 2. Define an infinite loop to allow users to continuously guess data.
        
        Scanner sc = new Scanner(System.in);
        while (true) {
            // Prompt the user to guess
            System.out.println("Please enter your guessed data:");
            int guessNumber = sc.nextInt();

            // 3. Determine the size of the number guessed by the user and the lucky number
            if(guessNumber > luckNumber){
                System.out.println("The number you guessed is too large~~");
            }else if(guessNumber < luckNumber){
                System.out.println("The number you guessed is too small~~");
            }else {
                System.out.println("Congratulations, your guess was successful and you can pay the bill~~");
                break; //End the infinite loop
            }
        }
    }
}