Logic control of Java

Posted by tomcurcuruto on Thu, 28 Oct 2021 05:10:34 +0200

catalogue

1, if statement

2, switch statement

3, while loop

4, for loop

5, do...while loop

6, Special statements in a loop

1. break statement

2. continue statement

7, Input and output in Java

1. Output

2. Input

Use Scanner to read string / integer / floating point number

Use the Scanner loop to read N numbers

Guess numbers games

Logical control is an indispensable part of all the program world. In fact, it is the same in life (choose primary school, choose high school, choose university, choose object, choose public entrance examination, postgraduate entrance examination, go abroad or work directly...) life is full of choices everywhere. Sometimes the results are not satisfactory. Don't lose heart and give up, because the opportunity is uncertain. It's waiting for you at the corner of the next choice~

In fact, the world of Java is inseparable from the choice of logic control. Next, let's take you to some basic logic control statements in Kangkang Java.

1, if statement

1. Syntax form of if statement:

if(Boolean expression){
   //Execute code when conditions are met
}
2. Syntax form of if...else statement:
if(Boolean expression){
   //Execute code when conditions are met
}else{
   //Execute code when conditions are not met
}

3,if...else if...else   Statement syntax form:
if(Boolean expression){
   //Execute code when conditions are met
}else if(Boolean expression){
   //Execute code when conditions are met
}else{
   //Execute code when none of the conditions are met
}

After speaking so much grammar, let's give an example.

Judge whether a year is a leap year as follows:

int year = 2000;
if (year % 100 == 0) {
    // Determine whether it is a leap year of the century
    if (year % 400 == 0) {
        System.out.println("It's a leap year");
   } else {
        System.out.println("Not a leap year");
   }
} else {
    // Determine whether it is an ordinary leap year
    if (year % 4 == 0) {
        System.out.println("It's a leap year");
Bit technology
   } else {
        System.out.println("Not a leap year");
   }
}

be careful:

1. if...else statements can be made without parentheses. But you can also write statements ( Only one statement can be followed. If you write multiple statements, the system will only default that the statement following it is the statement in if / else ).
2. If there are multiple if conditional sentences and there is only one else, then else   Yes and Closest if Match.
int x = 10;
int y = 10;
if (x == 10) 
 if (y == 10)
 System.out.println("aaa");
else
 System.out.println("bbb");
//Because else matches the nearest if, the output is aaa

2, switch statement

Basic syntax:
switch( ){
     case Content 1 : {
     Execute statement when content is satisfied;
     break;
 }
     case Content 2 : {
     Execute statement when content is satisfied;
     break;
 }
 ...
     default:{
     Execute the statement when the content is not satisfied;
     break;
 } 
}
Example: according to day The value of the output week.
int day = 1;
switch(day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    case 5:
        System.out.println("Friday");
        break;
    case 6:
        System.out.println("Saturday");
        break;
    case 7:
        System.out.println("Sunday");
        break;
    default:
        System.out.println("Incorrect input");
        break; }
according to switch Difference in median , The corresponding will be executed case sentence . encounter break Will end the case sentence.
If switch The value in does not match case, Will execute default Statements in.
be careful:
1. Be careful not to omit break. If it is omitted, it will not jump out of the loop immediately after meeting the conditions, but will continue to execute. It will output the subsequent value until it encounters the break statement, so we can't get the desired result.

2. The value in switch can only be int / byte / short  / enum / char / String.  

  long     float     double   boolean cannot be used as a switch parameter.

3, while loop

Basic syntax format:

while(Cycle condition){ 
Circular statement; 
}
If the cycle condition is true, Execute a circular statement; Otherwise, end the cycle.
be careful:
1. There must be conditions that can break the cycle, otherwise it will become an endless cycle.
2, and if similar, while The following statement may not be written { } , However, only one statement can be supported when it is not written.
Speaking of so much syntax, let's have an example of a while loop.
1, calculation 5 Factorial of.
int n = 1; 
int result = 1; 
while (n <= 5) { 
 result *= n; //This step is equivalent to result=n*result
 n++; 
} 
System.out.println(num); // The execution result is 120

2. Calculate 1+ 2! + 3! + 4! + 5!  

int num = 1; 
int sum = 0; 
while (num <= 5) { // The outer loop is responsible for finding the sum of factorials
 int factorResult = 1; 
 int tmp = 1; 
 while (tmp <= num) { // The inner loop is responsible for finding the value of each factorial
 factorResult *= tmp; 
 tmp++; 
 } 
 sum += factorResult; 
 num++; 
} 
System.out.println("sum = " + sum);

4, for loop

Basic syntax:
for(Expression 1;Expression 2;Expression 3){ 
Circulatory body; 
}
expression 1: Used to initialize loop variables.
Expression 2: loop condition.
Expression 3: update loop variable.
Example 1: calculate the factorial of 5.
int result = 0; 
for (int i = 1; i <= 5; i++) { 
 result *= i; 
} 
System.out.println("result = " + result);

Example 2: calculation 1+ 2! + 3! + 4! + 5!

int sum = 0; 
for (int i = 1; i <= 5; i++) { //The number of external circulation is five as required
 int tmp = 1; 
 for (int j = 1; j <= i; j++) { //Find the factorial of each number in the inner loop
 tmp *= j; 
 } 
 sum += tmp; 
} 
System.out.println("sum = " + sum);

(error prone point of this question: when defining tmp, remember to put it outside the inner loop and in the outer loop. If it is placed outside the outer loop, tmp will only be initialized once, and there will be problems in subsequent factorization, so we can't get the desired results.)

5, do...while loop

Basic syntax format:

do{ 
Circular statement; 
}while(Cycle condition);
Execute the loop statement first , Then determine the cycle conditions. (some people get on the bus first and then make up the ticket / / it's like cutting first and playing later)
Example: print 1 ~ 10.
int num = 1; 
do { 
 System.out.println(num); 
 num++; 
} while (num <= 10); 

Note: don't forget the semicolon at the end of the do...while loop. Generally, do while uses less, while and for loops use the most.

6, Special statements in a loop

1. break statement

break The function of is to end the cycle ahead of time.

Example: find 100~   The first number in 200 is a multiple of 3 and printed.

int num = 100; 
while (num <= 200) { 
 if (num % 3 == 0) { 
 System.out.println("A multiple of 3 was found, by:" + num); 
 break; 
 } 
 num++; 
} 
// The execution result found a multiple of 3: 102

This shows that break can jump out of the loop. If there are nested loops, break will jump out of the nearest loop.

2. continue statement

continue The function of is to skip this cycle , Immediately enter the next cycle.
Example: find 100 - 200 All in 3 Multiple of
int num = 100; 
while (num <= 200) { 
 if (num % 3 != 0) { 
 num++;
 continue; 
 } 
 System.out.println("A multiple of 3 was found, by:" + num); 
 num++; 
}
As can be seen from the above, the continue statement immediately skips this cycle (ignoring the statements after continue) and directly to the judgment conditions. If it meets the judgment conditions, then execute the next cycle, but not directly jump out of the whole cycle.

7, Input and output in Java

1. Output

This is also mentioned in the first section of getting to know Java. There are three kinds of output in Java.

1,System.out.println("hello world");    // Output a string, With line feed.

2,System.out.print("hello world");    // Output a string without line breaks

3,  int a=77;

       System.out.printf("a=%d\n",a);     // As in c, format the output.

The following are some formatting Converters:

2. Input

Use Scanner to read string / integer / floating point number

import java.util.Scanner; // When using Scanner, you need to import util package
Scanner sc = new Scanner(System.in); 
System.out.println("Please enter your name:"); 
String name = sc.nextLine();   //Read a string
System.out.println("Please enter your age:"); 
int age = sc.nextInt();        //Read an integer
System.out.println("Please enter your salary:"); 
float salary = sc.nextFloat(); //Read a floating point number
System.out.println("Your information is as follows:"); 
System.out.println("full name: "+name+"\n"+"Age:"+age+"\n"+"Salary:"+salary); 


// results of enforcement
 Please enter your name:
Zhang San
 Please enter your age:
18 
Please enter your salary:
1000 
Your information is as follows:
full name: Zhang San
 Age: 18 
Salary: 1000.0 

Of course, in addition to the above, data types such as nextBoolean (), nextByte (), nextShort () are also supported.

Use the Scanner loop to read N numbers

 Scanner sc = new Scanner(System.in);
 while (sc.hasNextDouble() ){
     .....
}
The available statements are as follows. The return values of these methods are of boolean type, indicating that if the value of this type is always input, the process of reading numbers - executing programs will continue.
(generally speaking, it may be used to brush questions, because there are usually several groups of use cases to pass, so circular input is required.)

 

How can it end?

use ctrl + z To end the input (Windows Use on ctrl + z, Linux / Mac Use on ctrl + d) to end.

 

Guess numbers games

Finally, write a guessing game to end this article~

Expand the usage of random (also import util package before use)——

random random = new Random();  // The default random seed is system time
int guess= random.nextInt(100);      // The range of random values representing guess variables is [0 ~ 100)   Left closed right open
Of course, there are other types——

 

import java.util.Random; 
import java.util.Scanner;
class Test { 
 public static void main(String[] args) { 
 Random random = new Random(); 
 Scanner sc = new Scanner(System.in); 
 int guess = random.nextInt(100); 
 while (true) { 
     System.out.println("Please enter the number you want to enter: (1-100)"); 
     int num = sc.nextInt(); 
         if (num < guess) { 
             System.out.println("Low"); 
         } else if (num > guess) { 
             System.out.println("High"); 
         } else { 
             System.out.println("You guessed right"); 
             break; 
         } 
     } 
  } 
}

  The final running result is:

  Isn't it very interesting? After learning the loop and logic, you can write more interesting games.

The next article is about the use of methods (functions). I really think I'm so slow to write. Hahaha

to be continue →

Welcome to discuss and exchange with each other. Welcome to catch insects!

 

 

 

Topics: Java Back-end