Branch, Loop, Random Explanation

Branch structure:

  • Branching structures in Java include if statement, switch statement and ternary operator. The if statement is the most commonly used branch structure, and its syntax is:

    • if statement

      • basic sentence
        • if (condition) {
            // 如果 condition 成立,执行此处代码块
          }
      • For example, we can use an if statement to check whether a number is even:

        • int num = 10;
          if (num % 2 == 0) {
            System.out.println(num + " 是偶数");
          }
      • The switch statement is useful when we need to check if a variable is equal to multiple values. Its syntax is: add break to terminate the execution of the program in the switch, which has the same effect as if () else if () and can avoid the consumption of time by continuous if.
        • switch (variable) {
            case value1:
              // 如果 variable 等于 value1,执行此处代码块
              break;
            case value2:
              // 如果 variable 等于 value2,执行此处代码块
              break;
            default:
              // 如果 variable 不等于 value1 或 value2,执行此处代码块
              break;
          }
          
      • ​​​​​​For example , we can use a switch statement to output the time of day:
        • int hour = 14;
          switch (hour) {
            case 8:
            case 9:
            case 10:
              System.out.println("现在是上午");
              break;
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
              System.out.println("现在是中午");
              break;
            default:
              System.out.println("现在是下午或晚上");
              break;
          }
          
      • loop structure

        • The looping structures in Java include for loop, while loop and do-while loop. The for loop is suitable for situations where the number of loops is known, and its syntax is :

          • for:for(;;)

            • for (initialization; condition; update) {
                // 循环体
              }
            • For example, we can output the numbers from 1 to 10 using a for loop:
              • for (int i = 1; i <= 10; i++) {
                  System.out.println(i);
                }
                
          • Its syntax is:
            • while (condition) {
                // 循环体
              }
              
            • For example, we can use a while loop to calculate the sum from 1 to 100:
              • int i = 1;
                int sum = 0;
                while (i <= 100) {
                  sum += i;
                  i++;
                }
                System.out.println(sum);
                
          • The do-while loop is similar to the while loop, but its loop body will be executed at least once, and its syntax is:
            • do
              {
                  //执行内容
              }while(c);
            • For example, we can use a do-while loop to let the user enter a password until the password is entered correctly:
              • String pass = "p";
                String input;
                do {
                  System.out.println("请输入密码:");
                  input = scanner.nextLine();
                } while (!input.equals(pass));
                System.out.println("密码正确");
          • Random class

            • The Random class is a pseudo-random number generator class provided by Java, which can generate pseudo-random number sequences. Use the Random class to easily generate various scenarios that require random numbers, such as number guessing games, encryption, simulation, etc.

              The Random class has two commonly used constructors:

            • public Random(): Create a new random number generator, seeded with the current system time.
            • public Random(long seed): Creates a new random number generator, seeded with the specified seed.
            • The seed is the initial state of the random number generator, and different seeds will generate different sequences of pseudo-random numbers. If the Random object is created with the same seed, the resulting sequence of pseudo-random numbers is also the same.

              The Random class provides several methods to generate different types of random numbers:

            • public int nextInt(): Generate a pseudorandom integer.
            • public int nextInt(int n): Generates a pseudorandom integer between 0 (inclusive) and the specified value n (exclusive).
            • public long nextLong(): Generate a pseudorandom long integer.
            • public float nextFloat(): Generate a pseudo-random floating-point number with a range of [0.0f, 1.0f).
            • public double nextDouble(): Generate a pseudo-random double-precision floating-point number with a value range of [0.0d, 1.0d).
            • public boolean nextBoolean(): Generates a pseudorandom boolean value.
          • ​​​​​​​​Example:
            • ​​​​​​​​​​​​​​​​​​​​​​​​​​​​
              import java.util.Random;
              
              public class RandomExample {
                public static void main(String[] args) {
                  Random random = new Random();
                  System.out.println("生成一个伪随机整数:" + random.nextInt());
                  System.out.println("生成一个在0到10之间的伪随机整数:" + random.nextInt(10));
                  System.out.println("生成一个伪随机长整数:" + random.nextLong());
                  System.out.println("生成一个伪随机浮点数:" + random.nextFloat());
                  System.out.println("生成一个伪随机双精度浮点数:" + random.nextDouble());
                  System.out.println("生成一个伪随机布尔值:" + random.nextBoolean());
                }
              }
              
              ​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

Small game development: implement a guessing number game (time limit 20 minutes)  

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

public class GuessNumberGame {
  public static void main(String[] args) {
    Random random = new Random();
    int number = random.nextInt(100) + 1; // 生成1到100之间的随机数
    Scanner scanner = new Scanner(System.in);
    int guessCount = 0;
    while (guessCount < 10) {
      System.out.println("请输入你猜测的数字(1到100之间):");
      int guess = scanner.nextInt();
      if (guess == number) {
        System.out.println("恭喜你,猜对了!");
        return;
      } else if (guess < number) {
        System.out.println("你猜的数字太小了");
      } else {
        System.out.println("你猜的数字太大了");
      }
      guessCount++;
    }
    System.out.println("很遗憾,你没有猜中,正确答案是 " + number);
  }
}

Conclusion:

Recently, I have seen a lot of news about the cold winter of the Internet and the layoffs of major factories. After thinking for a long time, I still think that the Internet is one of the best industries in the future.

I want to send some encouragement and hope to all programmers who are in the winter of the Internet.

First, let me tell you that you are not alone. The entire Internet industry is going through a cold winter period, and this situation is not static. There have been many booms and busts in the Internet industry in history, but every winter will usher in spring with the rise of new technologies and business models. Therefore, only by believing in the future development prospects and insisting on moving forward can we win in the competition.

Second, I would like to remind you to keep learning enthusiasm and creative minds. The Internet industry is an industry full of changes and constant updates. Only by continuous learning and innovation can we keep up with the trend. At the same time, learn to learn from failures and setbacks, sum up lessons learned, and make yourself more mature and stable.

Finally, I want to encourage you to always stick to your beliefs and pursuits. There are many outlets and hot spots in the Internet industry, but only your deepest beliefs and pursuits are the real driving force. Only by firmly pursuing your own goals and dreams can you achieve greater success and achievements in future competition.

In short, I hope that the above words can bring some encouragement and inspiration to all programmers in the cold winter of the Internet, so that everyone can meet the challenges and opportunities in the future together. At the same time, we must always adhere to the concept of innovation and value creation to make our Internet industry more vibrant and vibrant.

If there is an error, please contact the author to change it.

        

Guess you like

Origin blog.csdn.net/screamn/article/details/129937788